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


当前回答

在Java 9中

使用不同的IntStream.iterate和IntStream.takeWhile方法:

int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();

Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]


int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();

Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

在Java 10中

使用局部变量类型推断:

var letters = new String[]{"A", "B", "C"};

其他回答

公告

一维阵列

int[] nums1; // best practice
int []nums2;
int nums3[];

多维数组

int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];

声明和初始化

一维阵列

使用默认值

int[] nums = new int[3]; // [0, 0, 0]

Object[] objects = new Object[3]; // [null, null, null]

带数组文字

int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};

Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};

带有循环

int[] nums = new int[3];
for (int i = 0; i < nums.length; i++) {
    nums[i] = i; // can contain any YOUR filling strategy
}

Object[] objects = new Object[3];
for (int i = 0; i < objects.length; i++) {
    objects[i] = new Object(); // can contain any YOUR filling strategy
}

带循环for和Random

int[] nums = new int[10];
Random random = new Random();
for (int i = 0; i < nums.length; i++) {
    nums[i] = random.nextInt(10); // random int from 0 to 9
}

使用流(从Java 8开始)

int[] nums1 = IntStream.range(0, 3)
                       .toArray(); // [0, 1, 2]
int[] nums2 = IntStream.rangeClosed(0, 3)
                       .toArray(); // [0, 1, 2, 3]
int[] nums3 = IntStream.of(10, 11, 12, 13)
                       .toArray(); // [10, 11, 12, 13]
int[] nums4 = IntStream.of(12, 11, 13, 10)
                       .sorted()
                       .toArray(); // [10, 11, 12, 13]
int[] nums5 = IntStream.iterate(0, x -> x <= 3, x -> x + 1)
                       .toArray(); // [0, 1, 2, 3]
int[] nums6 = IntStream.iterate(0, x -> x + 1)
                       .takeWhile(x -> x < 3)
                       .toArray(); // [0, 1, 2]

int size = 3;
Object[] objects1 = IntStream.range(0, size)
        .mapToObj(i -> new Object()) // can contain any YOUR filling strategy
        .toArray(Object[]::new);

Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy
        .limit(size)
        .toArray(Object[]::new);

使用Random和Stream(从Java 8开始)

int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();

多维数组

使用默认值

int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]

带数组文字

int[][] nums1 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
int[][] nums2 = new int[][]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

Object[][] objects1 = {
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};

带有循环

int[][] nums = new int[3][3];
for (int i = 0; i < nums.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        nums[i][j] = i + j; // can contain any YOUR filling strategy
    }
}

Object[][] objects = new Object[3][3];
for (int i = 0; i < objects.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        objects[i][j] = new Object(); // can contain any YOUR filling strategy
    }
}

此外,如果您需要更动态的内容,可以使用List界面。这不会表现得很好,但更灵活:

List<String> listOfString = new ArrayList<String>();

listOfString.add("foo");
listOfString.add("bar");

String value = listOfString.get(0);
assertEquals( value, "foo" );

下面显示了数组的声明,但未初始化数组:

 int[] myIntArray = new int[3];

下面显示了数组的声明和初始化:

int[] myIntArray = {1,2,3};

现在,下面还显示了数组的声明和初始化:

int[] myIntArray = new int[]{1,2,3};

但第三个显示了匿名数组对象创建的属性,该属性由引用变量“myIntArray”指向,因此如果我们只写“newint[]{1,2,3};”,那么这就是如何创建匿名数组对象。

如果我们只写:

int[] myIntArray;

这不是数组的声明,但以下语句使上述声明完成:

myIntArray=new int[3];

数组是项目的顺序列表

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

如果它是一个物体,那么它就是同一个概念

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

对于对象,您需要将其赋值为null,以使用新的Type(..)初始化它们,像String和Integer这样的类是特殊情况,将按如下方式处理

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

通常,您可以创建M维数组

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

值得注意的是,从空间角度来看,创建M维阵列是昂贵的。因为当您在所有维度上创建一个N的M维数组时,数组的总大小大于N^M,因为每个数组都有一个引用,并且在M维有一个(M-1)维引用数组。总尺寸如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data
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};