java-initialize-array
Initializing Arrays in Java
1. Overview
2. One Element at a Time
for (int i = 0; i < array.length; i++) {
array[i] = i + 2;
}
And let’s 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
String array[] = new String[] {
"Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };
While instantiating the array, we do not 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()
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:
long array[] = new long[5];
Arrays.fill(array, 30);
The method also has several alternatives which set a 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()
The method Arrays.copyOf() creates a new array by copying another array. The method has many overloads which accept different types of arguments.
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 gets thrown
-
If the source array length is negative, then a NegativeArraySizeException is thrown
6. Using 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.
7. Using 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:
char[] array = new char[] {'a', 'b', 'c'};
char[] copy = ArrayUtils.clone(array);
Note that this method is overloaded for all primitive types.
8. Conclusion
As always, the full version of the code is available over on GitHub.