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[] 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);
            System.out.print(myA[i].x);
        }
    }
}

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: Collection, Map

Java

  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface

Package

  1. Package

Misc

  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals