Creating an array of objects in Java
You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:
A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
Stream.generate(() -> new A())
is like factory for separate A elements created in a way described by lambda,() -> new A()
which is implementation ofSupplier<A>
- it describe how each new A instances should be created.limit(4)
sets amount of elements which stream will generatetoArray(A[]::new)
(can also be rewritten astoArray(size -> new A[size])
) - it lets us decide/describe type of array which should be returned.
For some primitive types you can use DoubleStream
, IntStream
, LongStream
which additionally provide generators like range
rangeClosed
and few others.
This is correct.
A[] a = new A[4];
...creates 4 A
references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod()
without allocating a1
like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
Yes, it creates only references, which are set to their default value null. That is why you get a NullPointerException You need to create objects separately and assign the reference. There are 3 steps to create arrays in Java -
Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty.
Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions.
Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations.
Declaring Arrays In Java
This is how we declare a one-dimensional array in Java –
int[] array; int array[];
Oracle recommends that you use the former syntax for declaring arrays. Here are some other examples of legal declarations –
// One Dimensional Arrays int[] intArray; // Good double[] doubleArray; // One Dimensional Arrays byte byteArray[]; // Ugly! long longArray[]; // Two Dimensional Arrays int[][] int2DArray; // Good double[][] double2DArray; // Two Dimensional Arrays byte[] byte2DArray[]; // Ugly long[] long2DArray[];
And these are some examples of illegal declarations –
int[5] intArray; // Don't mention size! double{} doubleArray; // Square Brackets please!
Instantiation
This is how we “instantiate”, or allocate memory for an array –
int[] array = new int[5];
When the JVM encounters the
new
keyword, it understands that it must allocate memory for something. And by specifyingint[5]
, we mean that we want an array ofint
s, of size 5. So, the JVM creates the memory and assigns the reference of the newly allocated memory to array which a “reference” of typeint[]
Initialization
Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.
All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax –
int[] arr = {1, 2, 3, 4, 5};
Here, we don’t mention the size, because JVM can see that we are giving 5 values.
So, until we instantiate the references remain null. I hope my answer has helped you..! :)
Source - Arrays in Java
This is correct. You can also do :
A[] a = new A[] { new A("args"), new A("other args"), .. };
This syntax can also be used to create and initialize an array anywhere, such as in a method argument:
someMethod( new A[] { new A("args"), new A("other args"), . . } )