To initialize a generic array in Java, you can use the new
operator and the Array
class.
Here is an example of how to initialize a generic array of integers in Java:
Integer[] array = new Integer[5];
This creates a new array of integers with a length of 5. All the elements of the array will be initialized to their default values (null
for objects, 0
for numeric types, and false
for booleans).
To initialize the elements of the array with specific values, you can use a loop or an array initializer:
// Using a loop for (int i = 0; i < array.length; i++) { array[i] = i; } // Using an array initializer Integer[] array = {1, 2, 3, 4, 5};
In these examples, the elements of the array are initialized with the values 0, 1, 2, 3, and 4, or 1, 2, 3, 4, and 5, respectively.
Note that the Array
class is a utility class that provides static methods for creating, accessing, and manipulating arrays. It is not a class that you can create instances of.
For more information on arrays and the Array
class in Java, you can refer to the Java documentation.