GNGiseldo Neo and Alana NeoBooks
Introduction to Programming in Java8 / 25

Lists and Collections

Storing variable quantities of data

7.1 Learning objectives

By the end of this chapter, you should be able to:

  • explain the difference between an array and a list;
  • declare a variable using the List interface;
  • add, query, update, and remove elements;
  • iterate over a list without accessing invalid indices;
  • use generics for compile-time type safety.

7.2 List and ArrayList

A list can grow and shrink at runtime.

Figure 7.1. A list can grow and shrink at runtime.

Arrays have a fixed size. An ArrayList can grow or shrink at runtime. Prefer declaring the variable with the List interface:

import java.util.ArrayList;
import java.util.List;

List<String> history = new ArrayList<>();
history.add("hi");
history.add("help");

The type inside < > specifies which elements are accepted. List<String> rejects numbers and other types at compile time.

7.3 Essential operations

history.add("tip");
String first = history.get(0);
history.set(0, "HI");
history.remove("tip");

System.out.println(history.size());
System.out.println(history.isEmpty());
System.out.println(history.contains("help"));

Valid indices range from zero to size() - 1. If an index comes from user input, validate it before calling get, set, or remove.

7.4 Complete example

import java.util.ArrayList;
import java.util.List;

public class Chapter07Collections {
    public static void main(String[] args) {
        List<String> history = new ArrayList<>();
        history.add("hi");
        history.add("help");
        history.add("tip");

        for (String message : history) {
            System.out.println("User: " + message);
        }

        String last = history.get(history.size() - 1);
        System.out.println("Last message: " + last);
        System.out.println("Total: " + history.size());
    }
}

7.5 Copies and state exposure

If a class returns its internal list directly, external code can modify it without going through the class’s rules. Returning a read-only copy avoids this problem:

public List<String> getHistory() {
    return List.copyOf(history);
}

7.6 Autoboxing

Collections store objects. For integer numbers, use Integer instead of int:

List<Integer> scores = new ArrayList<>();
scores.add(10); // int converted to Integer

The automatic conversion between int and Integer is called autoboxing and unboxing.

7.7 Project evolution: version 7

Replace the standalone counter with a list of valid messages. The history command should read the list without being added to it; that way, “total messages” means only user messages processed prior to the query.

The complete example is in examples/src/Chapter07Collections.java.

7.8 Verifiable practice

Implement methods to:

  1. record a non-empty message;
  2. return the last message;
  3. return at most the three most recent messages;
  4. limit the history to ten items.

Test cases:

StateExpected result
empty listmessage “No history”
two itemsboth appear, in order
twelve insertions with a limit of tenonly the last ten remain

Choosing a data structure

Use an array when the size is part of the rule. Use List when the number of items varies at runtime.