Java: 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[] xx;         // declare type
        xx = new H[4];  // set value, as array of object H, 4 of them

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

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

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

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

Java, data structures, array, collection, map