Create a Collection Class in Java - dummies

By Barry Burd

A collection class in Java code is a class whose job is to store a bunch of objects at a time — a bunch of String objects, a bunch of BagOfCheese objects, a bunch of tweets, or whatever. You can create a collection class with this code.

package com.allmycode.collections;
import java.util.ArrayList;
public class SimpleCollectionsDemo {
  public static void main(String[] args) {
    ArrayList arrayList = new ArrayList();
    arrayList.add("Hello");
    arrayList.add(", ");
    arrayList.add("readers");
    arrayList.add("!");
    for (int i = 0; i < 4; i++) {
      System.out.print(arrayList.get(i));
    }
  }
}

When you run the code in the listing, you see the output shown in this figure.

Running the code in the listing.
Running the code in the listing.

The code constructs a new ArrayList instance and makes the arrayList variable refer to that new instance. The ArrayList class is one of many kinds of collection classes.

The statement ArrayList arrayList = new ArrayList() creates an empty list of things and makes the arrayList variable refer to that empty list. What does a list look like when it’s empty? Anyway, the difference between having an empty list and having no list is important. Before executing ArrayList arrayList = new ArrayList(), you have no list. After executing ArrayList arrayList = new ArrayList(), you have a list that happens to be empty.

The code in the listing calls arrayList.add four times in order to put these four objects (all strings) into the list:

  • “Hello”

  • “, “

  • “readers”

  • “!”

After calling arrayList.add, the list is no longer empty.

To display the objects in Eclipse’s Console view, the code calls System.out.print four times, each time with a different object from the arrayList collection.

If you don’t see Eclipse’s Console view, click Window→Show View→Console.

There’s a difference between System.out.println and System.out.print (without the ln ending): The System.out.println method goes to a new line after displaying its text; the System.out.print method does not go to a new line after displaying its text. In the listing, for example, with four calls to System.out.print, all four chunks of text appear on the same line in Eclipse’s Console view.

The for statement in the listing marches through the values in the arrayList. Every value in the list has an index, each ranging from 0 to 3.

In a Java collection, the initial index is always 0, not 1.