Home  >  Article  >  Java  >  How do you create an array of objects in Java?

How do you create an array of objects in Java?

DDD
DDDOriginal
2024-10-28 08:21:30544browse

How do you create an array of objects in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn