如何在Java中声明和初始化数组?


当前回答

制作阵列有两种主要方法:

对于空数组:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array

对于一个初始化的数组:

int[] array = {1,2,3,4 ...};

您还可以创建多维数组,如下所示:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

其他回答

int[] x = new int[enter the size of array here];

例子:

int[] x = new int[10];
              

Or

int[] x = {enter the elements of array here];

例子:

int[] x = {10, 65, 40, 5, 48, 31};

有多种方法可以在Java中声明数组:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};

您可以在Sun教程网站和JavaDoc中找到更多信息。

有两种类型的阵列。

一维阵列

默认值的语法:

int[] num = new int[5];

或(不太优选)

int num[] = new int[5];

给定值的语法(变量/字段初始化):

int[] num = {1,2,3,4,5};

或(不太优选)

int num[] = {1, 2, 3, 4, 5};

注意:为了方便起见,最好使用int[]num,因为它清楚地告诉您在这里讨论的是数组。否则没有区别。一点也不。

多维数组

公告

int[][] num = new int[5][2];

Or

int num[][] = new int[5][2];

Or

int[] num[] = new int[5][2];

初始化

 num[0][0]=1;
 num[0][1]=2;
 num[1][0]=1;
 num[1][1]=2;
 num[2][0]=1;
 num[2][1]=2;
 num[3][0]=1;
 num[3][1]=2;
 num[4][0]=1;
 num[4][1]=2;

Or

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

杂乱阵列(或非矩形阵列)

 int[][] num = new int[5][];
 num[0] = new int[1];
 num[1] = new int[5];
 num[2] = new int[2];
 num[3] = new int[3];

所以这里我们是显式定义列。另一种方式:

int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };

用于访问:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}

或者:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}

杂乱数组是多维数组。有关说明,请参阅官方java教程中的多维数组详细信息

制作阵列有两种主要方法:

对于空数组:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array

对于一个初始化的数组:

int[] array = {1,2,3,4 ...};

您还可以创建多维数组,如下所示:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

声明对象引用数组:

class Animal {}

class Horse extends Animal {
    public static void main(String[] args) {

        /*
         * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
         */
        Animal[] a1 = new Animal[10];
        a1[0] = new Animal();
        a1[1] = new Horse();

        /*
         * Array of Animal can hold Animal and Horse and all subtype of Horse
         */
        Animal[] a2 = new Horse[10];
        a2[0] = new Animal();
        a2[1] = new Horse();

        /*
         * Array of Horse can hold only Horse and its subtype (if any) and not
           allowed supertype of Horse nor other subtype of Animal.
         */
        Horse[] h1 = new Horse[10];
        h1[0] = new Animal(); // Not allowed
        h1[1] = new Horse();

        /*
         * This can not be declared.
         */
        Horse[] h2 = new Animal[10]; // Not allowed
    }
}