The ListItem Class

Let’s return to our original question: how would we implement a list if Java did not have built-in arrays? We can use the idea of a chain of objects that we just discussed with the Employee class. We can create a class called ListItem that represents an item in the list. Each ListItem will have a field to store the data (the value of the item) and a field to reference the next ListItem in the list. Here is how we can define the ListItem class:

public class ListItem {
  public int value;  // the data stored in this item
  public ListItem next;  // reference to the next item in the list
}

I have made some design choices here. Let’s go through them:

  • The value field is of type int, so our list will store integers. We could make this more flexible with a generic type, but for simplicity, we will use integers for now.
  • We could store more data in the ListItem class (just like the Employee class has an id and name), but we will keep it simple here and only store the value of the item.
  • The next field is of type ListItem, so it references another ListItem object in the list. We could add more reference fields, like a prev field to reference the previous item, but for now we use a single reference to the next item.
  • The ListItem class and its fields are public. This goes against the principle of encapsulation and information hiding, and we will fix it later.

Note that the ListItem class does have a constructor even though we did not explicitly define one. In Java, if you do not define a constructor, the compiler provides a default no-argument constructor. Fields that are not explicitly initialized get their default values (0 for int and null for reference types).

So when we create a new ListItem, its value will be initialized to 0 and its next will be initialized to null.

ListItem item = new ListItem();
System.out.println(item.value);  // prints 0
System.out.println(item.next);  // prints null

item.value = 5;  // we can set the value to something else
System.out.println(item.value);  // prints 5

We can add a constructor to the ListItem class if we want to initialize the value when we create a new item. Here is how we can do that:

public class ListItem {
  public int value;
  public ListItem next;

  // constructor to initialize the value
  public ListItem(int value) {
    this.value = value;
    this.next = null;  // not needed,
                       // but makes it explicit that the next item is null,
                       // when we create a new item
  }
}

Now we can create a new ListItem and set its value in one step:

ListItem item = new ListItem(5);
System.out.println(item.value);  // prints 5
System.out.println(item.next);  // prints null