Creating Arrays of Objects in Java
When attempting to create an array of objects in Java, beginners may encounter an apparent discrepancy compared to languages like C . In C , simply declaring new A[4] suffices to create four objects, while in Java, this approach only creates references to objects rather than objects themselves.
The Correct Approach
To correctly create an array of objects in Java, the following approach is required:
<code class="java">A[] arr = new A[4]; for (int i = 0; i < 4; i++) { arr[i] = new A(); }</code>
This approach declares an array of references (A[] arr) and then iteratively assigns each element of the array to a new object (arr[i] = new A()).
Justification
In Java, arrays store references to objects, not the objects themselves. Therefore, the initial declaration A[] arr = new A[4]; only creates four references. To actually create the objects, each reference must be assigned to a new object instance.
Additional Notes
To access the functions and variables of the objects in the array, simply use the dot operator as usual:
<code class="java">arr[0].someMethod(); int value = arr[1].someVariable;</code>
The above is the detailed content of How do you create an array of objects in Java?. For more information, please follow other related articles on the PHP Chinese website!