Initializing Arrays in Java – 在Java中初始化数组

最后修改: 2017年 10月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to examine the different ways that we can initialize an array, and the subtle differences between them.

在这个快速教程中,我们将研究初始化数组的不同方法,以及它们之间的微妙差别。

2. One Element at a Time

2.一次一个元素

Let’s start with a simple, loop-based method:

让我们从一个简单的、基于循环的方法开始。

for (int i = 0; i < array.length; i++) {
    array[i] = i + 2;
}

We’ll also see how we can initialize a multi-dimensional array one element at a time:

我们还将看到,我们如何每次都能对多维数组的一个元素进行初始化。

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 5; j++) {
        array[i][j] = j + 1;
    }
}

3. At the Time of Declaration

3.在宣布时

Now let’s initialize an array at the time of declaration:

现在让我们在声明的时候初始化一个数组。

String array[] = new String[] { 
  "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };

While instantiating the array, we don’t have to specify its type:

在实例化数组时,我们不必指定其类型。

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

Note that it’s not possible to initialize an array after the declaration using this approach; an attempt to do so will result in a compilation error.

注意,使用这种方法不可能在声明后初始化数组;试图这样做会导致编译错误。

4. Using Arrays.fill()

4.使用Arrays.fill()

The java.util.Arrays class has several methods named fill(), which accept different types of arguments and fill the whole array with the same value:

java.util.Arrays类有几个名为fill()的方法,它们接受不同类型的参数并以相同的值填充整个数组。

long array[] = new long[5];
Arrays.fill(array, 30);

The method also has several alternatives, which set the range of an array to a particular value:

该方法也有几个备选方案,将数组的范围设置为一个特定的值。

int array[] = new int[5];
Arrays.fill(array, 0, 3, -50);

Note that the method accepts the array, the index of the first element, the number of elements, and the value.

注意,该方法接受数组,第一个元素的索引,元素的数量,以及值。

5. Using Arrays.copyOf()

5.使用Arrays.copyOf()

The method Arrays.copyOf() creates a new array by copying another array. The method has many overloads, which accept different types of arguments.

方法Arrays.copyOf()通过复制另一个数组来创建一个新数组。该方法有许多重载,接受不同类型的参数。

Let’s see a quick example:

让我们看一个快速的例子。

int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 5);

A few notes here:

这里有一些说明。

  • The method accepts the source array and the length of the copy to be created.
  • If the length is greater than the length of the array to be copied, then the extra elements will be initialized using their default values.
  • If the source array has not been initialized, then a NullPointerException is thrown.
  • Finally, if the source array length is negative, then a NegativeArraySizeException is thrown.

6. Using Arrays.setAll()

6.使用Arrays.setAll()

The method Arrays.setAll() sets all elements of an array using a generator function:

方法Arrays.setAll()使用生成器函数设置一个数组的所有元素。

int[] array = new int[20];
Arrays.setAll(array, p -> p > 9 ? 0 : p);

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

If the generator function is null, then a NullPointerException is thrown.

如果生成器函数为空,那么就会抛出一个NullPointerException

7. Using ArrayUtils.clone()

7.使用ArrayUtils.clone()

Finally, let’s utilize the ArrayUtils.clone() API out of Apache Commons Lang 3, which initializes an array by creating a direct copy of another array:

最后,让我们利用Apache Commons Lang 3中的ArrayUtils.clone() API,它通过创建另一个数组的直接拷贝来初始化一个数组。

char[] array = new char[] {'a', 'b', 'c'};
char[] copy = ArrayUtils.clone(array);

Note that this method is overloaded for all primitive types.

注意,这个方法对所有原始类型都是重载的。

8. Conclusion

8.结论

In this brief article, we explored different ways of initializing arrays in Java.

在这篇简短的文章中,我们探讨了Java中初始化数组的不同方法。

As always, the full version of the code is available over on GitHub.

一如既往,完整版本的代码可在GitHub上获得