3

How to initialize an Array in Java in 4 simple ways

 1 year ago
source link: http://www.mastertheboss.com/java/4-ways-to-initialize-an-array-in-java/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

This article discusses about array initialization in Java, showing multiple ways to initialize an array, some of them you probably don’t know!

How to declare an array in Java

Firstly, some background. Java classifies types as primitive types, user-defined types, and array types. An array type is a region of memory that stores values in equal-size and contiguous slots, which we call elements. You can declare an array with the element type and one or more pairs of square brackets that indicate the number of dimensions. A single pair of brackets means a one-dimensional array.

Example:

String array[];
String array[];

On the other hand, this is a two-dimensional array:

double[][] matrix;
double[][] matrix;

So you basically specify the datatype and the declared variable name. Mind it, declaring an array does not initialize it. You can initialize an array, and assign memory to it, by providing just the array size or also the content of the array.

How to init and set the array length

The following example shows how to initialize an array of Strings. The length of the array includes 2 elements:

String array[] = new String[2];
String array[] = new String[2];

How to init an array using Array Literal

The following examples shows how to initialize different elements -in a single line- using Array Literals:

String array[] = new String[] { "Pear", "Apple", "Banana" };
int[] datas = { 12, 48, 91, 17 };
char grade[] = { 'A', 'B', 'C', 'D', 'F' };
float[][] matrixTemp = { { 1.0F, 2.0F, 3.0F }, { 4.0F, 5.0F, 6.0F }};
int x = 1, y[] = { 1, 2, 3, 4, 5 }, k = 3;
String array[] = new String[] { "Pear", "Apple", "Banana" };
int[] datas = { 12, 48, 91, 17 };
char grade[] = { 'A', 'B', 'C', 'D', 'F' };
float[][] matrixTemp = { { 1.0F, 2.0F, 3.0F }, { 4.0F, 5.0F, 6.0F }};
int x = 1, y[] = { 1, 2, 3, 4, 5 }, k = 3;

You can of course also split the declaration from the assignment:

int[] array;
array = new int[]{2,3,5,7,11};
int[] array;
     
array = new int[]{2,3,5,7,11};

When retrieving an array by its index, it is important to remember that index starts from 0:

how to init an array in java

Therefore, you can retrieve it by id as follows:

for (int i =0;i < 5;i++) {
System.out.println(array[i]);
   for (int i =0;i < 5;i++) {
            System.out.println(array[i]);
   }

On the other hand, if you want to init a multidimensional array in a loop, you need to loop over the array twice. Example:

double[][] temperatures = new double[3][2];
for (int row = 0; row < temperatures.length; row++)
for (int col = 0; col < temperatures[row].length; col++)
temperatures[row][col] = Math.random()*100;
double[][] temperatures = new double[3][2];

for (int row = 0; row < temperatures.length; row++)
   for (int col = 0; col < temperatures[row].length; col++)
      temperatures[row][col] = Math.random()*100;

Finally, if you don’t need to operate on the array id, you can use the simplified for loop to iterate through the array:

int[] array = new int[]{2,3,5,7,11};
for (int a:array)
System.out.println(a);
int[] array = new int[]{2,3,5,7,11};

for (int a:array)
   System.out.println(a);

Initialization using Arrays.copyOf()

The java.util.Arrays.copyOf(int[] original,int newLength) method copies the specified array, eventually truncating or padding with zeros (if needed) so the copy has the specified length.

Example:

int[] array = new int[]{2,3,5,7,11};
int[] copy = Arrays.copyOf(array, 5);
int[] array = new int[]{2,3,5,7,11};
int[] copy =  Arrays.copyOf(array, 5);

A similar option also exists in the System packages, using the System.arraycopy static method:

int[] src = new int[]{2,3,5,7,11};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
int[] src  = new int[]{2,3,5,7,11};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );

The core difference is that Arrays.copyOf does not just copy elements, it also creates a new array. On the other hand, System.arrayCopy copies into an existing array.

In most cases, System.arrayCopy will be faster because it uses a direct native memory copy. Arrays.copyOf uses Java primitives to copy although the JIT compiler could do some clever special case optimization to improve the performance.

Using Arrays functions to fill an array

The method Arrays.setAll sets all elements of an array using a generator function. This is the most flexible option as it lets you use a Lambda expression to initialize an array using a generator. Example:

int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);
int[] arr = new int[10];
Arrays.setAll(arr, (index) -> 1 + index);

This can be useful, for example, to quickly initialize an Array of Objects:

Customer[] customerArray = new Customer[7];
// setting values to customerArray using setAll() method
Arrays.setAll(customerArray, i -> new Customer(i+1, "Index "+i));
Customer[] customerArray = new Customer[7];
// setting values to customerArray using setAll() method
Arrays.setAll(customerArray, i -> new Customer(i+1, "Index "+i));

A similar function is Arrays.fill which is the best choice if you don’t need to use a generator function but you just need to init the whole array with a value. Here is how to fill an array of 10 int with the value “1”:

int [] myarray = new int[10];
Arrays.fill(myarray, 1);
int [] myarray = new int[10];
Arrays.fill(myarray, 1);

Finally, if you want to convert a Collection of List objects into an array, you can use the .toArray() method on the Collection. Example:

List<String> list = Arrays.asList("Apple", "Pear", "Banana");
String[] array = list.toArray(new String[list.size()]);
List<String> list = Arrays.asList("Apple", "Pear", "Banana");
String[] array = list.toArray(new String[list.size()]);

Initialization using the Stream API

Finally, you can also use the Java 8 Stream API for making a copy of an Array into another. Let’s check with at an example:

String[] strArray = {"apple", "tree", "banana'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
String[] strArray = {"apple", "tree", "banana'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);

Arrays.stream also does a shallow copy of objects, when using non-primitive types.

Printing an Array in Java

Finally, to print an array and its values in Java, you can use the Arrays.toString() method or a loop to iterate over the array and print each element. Here’s an example of using the Arrays.toString() method:

int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
int[] arr = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));

Besides, please note that if you are using a nested array, then you have to use the Arrays.deepToString method instead:

System.out.println(Arrays.deepToString(deepArray));
System.out.println(Arrays.deepToString(deepArray));

Conclusion

In this tutorial we have covered four basic strategies to initialize, prefill and iterate over an array in Java.

Post Views: 1,145

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK