Java Tutorial: Array of Objects

By Xah Lee. Date: . Last updated: .

You can make a array of Objects in Java. Here is a example.

// array of objects

// some random class
class H {
    int x;
    H (int n) {x=n;}

public class A {
    public static void main(String[] args) {
        H[] myA;         // declare type
        myA = new H[4];  // set value, as array of object H, 4 of them

        // fill each element
        for (int i = 0; i < myA.length; i++) {
            myA[i] = new H(i);

The line H[] myA; declares that the variable myA is a datatype of array of H.

The line myA = new H[4]; assigns this variable myA a thing, and that thing is a array of 4 elements, and each element is of type H.

The line myA[i] = new H(i); sets the value for each slot of myA. And, that value being the instantiation of H with i as the init parameter to the constructor of H.

If you want to be able to resize array, use ArrayList. See: Java Tutorial: Collection, Map