Object-Oriented Programming with Java · Lecture Notes

Chapter 5: Collections

Real programs work not with single variables but with masses of data. A class roster, the words of a dictionary, and the pending jobs of a printer all consist of many elements. The array is the first tool for this job, but its size is fixed in advance, and it leaves insertion, deletion, and searching to the programmer. Java offers a ready-made library for this need: the Collections Framework. This note covers the library as four families. Lists hold elements in order, queues organize elements waiting to be processed, sets prevent duplicates, and maps bind a key to a value. For each family we trace which internal structure it uses, how long each operation takes, and when to choose it. Next come the iterator, the ready-made algorithms of the Collections class, and the Stream API, which processes collections like a pipeline. All programs were compiled and run with JDK 21; the outputs, the values in the trace tables, and the compiler messages are taken from those runs.

Learning outcomes

Getting to know the framework
Distinguish the interface, implementation, and algorithm elements of the Collections Framework; read the interface and class hierarchy; explain the benefit of declaring a variable with an interface type.
Working with generic types
Write type-safe code with generic types such as List<String>; use wrapper classes and autoboxing correctly for primitive types.
Choosing lists
Use the ArrayList, LinkedList, Vector, and Stack classes; draw their internal structures and compare the costs of their operations.
Using queues
Build first-in-first-out, priority, and last-in-first-out behavior with Queue, PriorityQueue, and ArrayDeque; trace how a binary heap works.
Choosing sets and maps
Choose among HashSet, TreeSet, HashMap, TreeMap, and their linked variants according to ordering and speed needs; write equals and hashCode for your own classes.
Traversing, sorting, streaming
Traverse and remove safely with an iterator; sort, shuffle, and search with Collections; write Comparable and Comparator; build filtering, mapping, and collecting pipelines with java.util.stream.

5.1The Collections Framework

The array is the most basic structure for holding values of the same type one after another. It is fast and reaches any element instantly by index. But it has two major shortcomings. The first is its size: an array created with new int[3] holds three elements for its entire lifetime. The second is the lack of ready-made operations: to ask whether an element is in the array, to delete an element from the middle, or to sort the array, you must write a loop every time. This section introduces the library that closes both gaps and its basic ideas.

5.1.1Why collections?

Definition 5.1

A collection is a data structure that stores and manages multiple elements in a single object. The Java Collections Framework is the whole of the ready-made interfaces, classes, and algorithms in the java.util package.

The first difference between a collection and an array is that its size is dynamic. The collection grows as elements are added and shrinks as they are removed. The second difference is the ready-made methods: add inserts, remove deletes, contains tells whether an element is present, and size gives the number of elements. These methods have been used and tested in millions of programs for years. A programmer who writes the same job by hand is far more likely to make mistakes than one who uses the library.

To see the difference concretely, let us try to store four numbers. If the array was created with three cells, the fourth value does not fit:

int[] arr = new int[3];      // size fixed: 3
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
// arr[3] = 40;  → ArrayIndexOutOfBoundsException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

When the commented-out line arr[3] = 40; is executed, Java throws an ArrayIndexOutOfBoundsException. The message states the problem clearly: an array of length 3 has no index 3. The valid indices are 0, 1, and 2. The same four values go into a list without any trouble:

List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);       // no problem: it grows
System.out.println(list);
System.out.println("size: " + list.size());
[10, 20, 30, 40]
size: 4

Here List<Integer> is the type of the variable: "a list of integers". new ArrayList<>() creates the actual object. The list starts out empty, and each add call appends the value at the end. println prints the list in square brackets with the elements separated by commas; this format is produced by the list's own toString method. size() gives how many elements the list holds at that moment.

The analogy in the slides explains this difference well. An array is like a bus with a fixed number of seats: once the seats are full, no new passenger can board. An ArrayList is a bus that grows as passengers increase. How the growth happens, that is, how the bus expands internally, is traced in detail in the section on lists.

5.1.2The four basic kinds

The dozens of classes in the framework fall into four basic kinds. Figure 5.1 shows each kind with a small example.

AliCanAliEce AliCanEce Ali → 85Can → 72 head: AliCanEce: tail
Figure 5.1: The four basic collection kinds. The list (Ali, Can, Ali, Ece) is ordered and allows duplicates. The set (Ali, Can, Ece) keeps only one of each element. The map binds keys to values (Ali → 85, Can → 72). In the queue, the element at the head leaves first.
  • List: elements are kept in a definite order, and each has an index. The same element may appear more than once. Examples are ArrayList and LinkedList.
  • Set: only unique elements are present. An element that already exists is not added a second time. Examples are HashSet and TreeSet.
  • Map: key → value pairs are held. Each key appears once, while values may repeat. Examples are HashMap and TreeMap.
  • Queue: elements waiting to be processed are held. Usually first in, first out (FIFO). Examples are LinkedList and PriorityQueue.

Besides these kinds, the framework pursues some common goals. The basic operations (insertion, removal, update, search) are performed with similar names in every kind, and all of them can be traversed with a for-each loop. The API is simple and consistent; whoever learns one kind can easily use the others. Each class is tuned for a particular data volume and access pattern. Thanks to generic types, an element of the wrong type is caught at compile time. Algorithms such as sorting, searching, and shuffling are ready-made, and misuse is reported with an exception. As a result, less code is written and the code that is written is more reliable.

5.1.3The interface and class hierarchy

The skeleton of the framework consists of interfaces. An interface says which methods a type will have, but does not write the bodies of those methods. Figure 5.2 shows the basic interfaces and the extension relations among them.

«interface»Iterable«interface»Collection«interface»List«interface»Queue«interface»Set«interface»Mapseparate hierarchy(not a Collection)
Figure 5.2: The hierarchy of the collection interfaces. Collection extends Iterable; List, Queue, and Set in turn extend Collection. Map is part of the framework, but does not extend Collection. The arrows with hollow triangle heads are UML notation and point to the extended super-interface.

At the top of the hierarchy stands Iterable. The only required method of this interface is iterator(). If a type is Iterable, it can be traversed with a for-each loop. Collection gathers the methods common to all collections: add, remove, size, contains, and others. List, Queue, and Set inherit these common methods and add their own. For example, access by index (get(i)) exists only in List.

Map, on the other hand, is a separate branch. An element of a map is not a single value but a key-value pair. A method that takes a single element, such as add(e), does not fit a map; in a map, insertion is done with put(key, value). That is why Map does not extend Collection and is not Iterable either. This has an important consequence: a map cannot be given directly to a for-each loop. Instead, the keys, the values, or the pairs of the map are obtained as separate views and those are traversed.

Below the interfaces are the classes that implement them. Figure 5.3 gives the most commonly used classes and the interfaces they implement all together.

«interface»Collection«interface»List«interface»Queue«interface»SetArrayListVectorStackLinkedListPriorityQueue«interface»DequeArrayDequeHashSetLinkedHashSet«interface»SortedSet«interface»NavigableSetTreeSetinterfaceclassextendsimplements
Figure 5.3: The hierarchy of the collection classes. Blue boxes are interfaces; they only define behavior. Green boxes are classes whose objects can be created with new. LinkedList implements both the List and the Deque interface.

The notable point in the figure is that a class can implement more than one interface. LinkedList is both a list (access by index) and a double-ended queue (insertion and removal at the front and the back). The same object offers the methods of whichever interface type the variable has. An object cannot be created from an interface type: if you write new List<>(), the compiler stops.

NewList.java:4: error: List is abstract; cannot be instantiated
        List<Integer> a = new List<>();
                          ^
1 error

The message says that List is abstract. An abstract type has no method bodies; the object is always supplied by a concrete class (ArrayList, LinkedList).

5.1.4The three elements of the framework

The Collections Framework consists of three elements, each with a separate job.

Interface
Defines how a data structure should behave, that is, it says what is to be done. List represents an ordered list: the elements are in a sequence, are accessed by index, and may repeat.
Implementation
The concrete class that implements the interface, that is, it determines how the work is done. ArrayList implements the List interface with a dynamic array; LinkedList implements the same interface with linked nodes.
Algorithm
Ready-made methods that do jobs such as sorting, searching, and shuffling. Most are found as static methods in the Collections class. Collections.sort() sorts a list.

The three elements can be seen together in a short piece of code:

List<String> list = new ArrayList<>();  // interface ← class
list.add("Red");
list.add("Blue");
Collections.sort(list);                  // algorithm
System.out.println(list);
[Blue, Red]

In the first line, the interface (List<String>) is on the left and the implementation (ArrayList) on the right. Collections.sort is the algorithm, and it arranges the list in its natural order, that is, alphabetical order for strings. Because "Blue" starts with B and "Red" with R, Blue comes first. The algorithm does not have to know which class the list belongs to; it works with the methods offered by the List interface. The same sort call also works on a LinkedList.

This arrangement is a modular design. Each component has a definite role and responsibility. Different implementations and algorithms can be used together through the same interface. Anyone who writes a new list class benefits from all the ready-made algorithms as soon as it implements the List interface.

5.1.5Programming to an interface

An interface defines a behavior; classes implement this behavior with their own methods. Each class uses a different storage scheme: ArrayList a dynamic array, LinkedList a doubly linked list, HashMap a key-value table. Each meets the requirements of a particular data structure. A good habit for the programmer is to declare variables and parameters with the interface type.

public class PrintList {
    // interface parameter: works with any List
    static void print(List<String> list) {
        for (String s : list) {
            System.out.print(s + " ");
        }
        System.out.println("(" + list.size() + " items)");
    }

    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        a.add("Apple");
        a.add("Pear");
        List<String> b = new LinkedList<>(a);  // a copy
        b.add("Cherry");
        print(a);
        print(b);
    }
}
Apple Pear (2 items)
Apple Pear Cherry (3 items)

The parameter of the print method has type List<String>. The method does not know whether the list given to it is an ArrayList or a LinkedList, and it does not need to. The for-each loop and the size() call inside are available on every list. In main, a is an ArrayList and b is a LinkedList. The expression new LinkedList<>(a) creates a new list filled with the elements of a; so b first contains Apple and Pear, and then Cherry is added. Both calls go to the same method, and it prints objects of two different classes in the same way.

The real benefit of this approach shows when a change is needed. If one day it turns out that insertions at the front of the list are very frequent and ArrayList is too slow, only the new line is changed. Since the type of the variable is already List, the rest of the code stays the same. Had the variable been declared with type ArrayList, every method signature that uses that type would have to change as well. Joshua Bloch's book Effective Java summarizes this principle as "refer to objects by their interfaces".

Common mistake

Calling a class-specific method through an interface-typed variable. If the variable is declared as List<String> l = new LinkedList<>();, then l.addFirst("x") does not compile, because addFirst is defined in Deque, not in List. The compiler looks at the type of the variable, not at the actual class of the object. If you need to work at the ends, declare the variable with type Deque<String>.

5.1.6Generic types and type safety

Definition 5.2

A generic type is a class or interface written with a type parameter. In List<E>, E stands for the element type; when you write List<String>, String takes the place of E and the type becomes "list of String". Type safety means that a value of the wrong type is caught at compile time.

List<String> names = new ArrayList<>();
names.add("Ali");
// names.add(42);           // compile error
String first = names.get(0);  // no cast needed

List<Integer> grades = new ArrayList<>();  // no List<int>
grades.add(85);               // boxing: int → Integer
int n = grades.get(0);        // unboxing → int
System.out.println(first + " " + n);
Ali 85

The element type is written inside the angle brackets (<>). names accepts only String. If the commented-out names.add(42) is uncommented, the program does not compile:

WrongType.java:5: error: incompatible types: int cannot be converted to String
        names.add(42);
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

The error is not postponed to run time; it is caught before the program ever runs. The second benefit is on the get side. The result of names.get(0) is directly a String; there is no need to write a cast.

Generics arrived with Java 5. In the earlier "raw" usage, the collection holds every element as an Object, and a wrong type shows up only at run time, as a ClassCastException when a read element is cast. A generic type catches the same mistake at compile time.

The empty <> on the right-hand side is called the diamond operator and has been available since Java 7. The compiler infers the type from the declaration on the left: List<String> names = new ArrayList<>(); means the same as new ArrayList<String>(). The diamond is written only on the new side; ArrayList<> a = … does not compile.

Collections hold only objects

The type parameter must be a reference type; primitive types such as int and double cannot be written there. This is the message from an attempt at List<int>:

PrimitiveType.java:4: error: unexpected type
        List<int> grades = new ArrayList<>();
             ^
  required: reference
  found:    int
1 error

The message says "a reference type was expected, int was found". For primitive types, the corresponding wrapper class of each is used. Table 5.1 gives the most common ones.

Table 5.1: Primitive types and their wrapper classes.
Primitive typeWrapper class
intInteger
doubleDouble
charCharacter
booleanBoolean
longLong

The conversion between a primitive value and a wrapper object happens automatically. In the line grades.add(85), 85 is an int, but the list expects an Integer. The compiler turns this call into grades.add(Integer.valueOf(85)); this is called autoboxing. In the line int n = grades.get(0), a conversion in the opposite direction takes place: the value inside the Integer object is obtained with intValue(). This is called unboxing.

Unboxing has a trap. If the wrapper reference is null, there is no value to extract from it. The value of a key that is absent from a map comes back as null, and when this value is assigned to an int, the program crashes:

import java.util.*;
public class EmptyBox {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<>();
        int n = m.get("missing");
    }
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null

The message shows the source of the error exactly: the value returned by Map.get is null, so intValue() cannot be called. There is no visible method call on this line; the compiler itself inserted the intValue() call. That is why such errors surprise at first glance.

First examples: a list and a map

To see the two basic structures side by side, let us build a list of names and a phone book:

// list of names (ArrayList)
List<String> nameList = new ArrayList<>();
nameList.add("Ahmet");
nameList.add("Ayse");
System.out.println(nameList);

// phone book (HashMap)
Map<String, String> phoneBook = new HashMap<>();
phoneBook.put("Ahmet", "555-1234");
phoneBook.put("Ayse", "555-9876");
System.out.println(phoneBook.get("Ahmet"));
[Ahmet, Ayse]
555-1234

ArrayList keeps the elements in insertion order; add appends at the end each time. HashMap, on the other hand, maps a key (the name) to a value (the number). We insert into the map with put(key, value) and find the value with get(key). phoneBook.get("Ahmet") does not scan the book from start to finish; it goes directly to a position computed from the key. How this speed is achieved is explained in the sections on sets and maps.

5.1.7The methods of the Collection interface

The Collection interface defines the methods common to all lists, sets, and queues. Table 5.2 gives these methods, their purposes, and their return types.

Table 5.2: The basic methods of the Collection<E> interface. E is the element type; ? (wildcard) means "any type".
MethodPurposeReturns
add(E e)adds the element to the collectionboolean: true if added
remove(Object o)removes the element from the collectionboolean: true if removed
size()gives the number of elementsint
isEmpty()is the collection empty?boolean
contains(Object o)is the element in the collection?boolean
containsAll(Collection<?> c)are all elements of c in this collection?boolean
clear()removes all elements—
toArray()converts the collection to an arrayObject[]
iterator()gives an iterator for traversalIterator<E>
forEach(Consumer<? super E> a)applies an action to each element (Java 8+)—

That add returns a boolean may look pointless at first. Adding to a list always succeeds, and add always returns true. In a set, however, the situation is different: if the element is already present it is not added, and add returns false. The common interface is designed to cover both cases. remove and contains take their parameter as an Object; they test the equality of elements with the equals method.

In the following example, the type of the variable is deliberately chosen to be Collection:

Collection<String> colors = new ArrayList<>();
colors.add("red");
colors.add("green");
colors.add("blue");
System.out.println(colors.size());
System.out.println(colors.contains("green"));
colors.remove("green");
System.out.println(colors);
Collection<String> wanted = Arrays.asList("blue", "red");
System.out.println(colors.containsAll(wanted));
Object[] arr = colors.toArray();
System.out.println(arr.length);
colors.clear();
System.out.println(colors.isEmpty());
3
true
[red, blue]
true
2
true

The program proceeds line by line as follows. After three colors are added, size() is 3. contains("green") returns true. remove("green") finds the element by value and deletes it; the list becomes [red, blue]. Arrays.asList("blue", "red") creates a two-element list. containsAll asks whether every element of that list is in colors; order does not matter, and the result is true. toArray() copies the elements into a new array; the length of the array is 2. This array is independent of the collection: a change made in the array does not affect the collection. Finally, clear() deletes everything and isEmpty() returns true.

Because the variable has type Collection, only the common methods can be used. Even though the object is in reality an ArrayList, colors.get(0) does not compile:

CollGet.java:6: error: cannot find symbol
        String s = colors.get(0);
                         ^
  symbol:   method get(int)
  location: variable colors of type Collection<String>
1 error

The message says that a variable of type Collection<String> has no method named get(int). This is the flip side of the rule of programming to an interface: the type of the variable determines which methods can be called. All the methods of Collection, on the other hand, exist on every List, Set, and Queue object.

5.2Lists

The list is the most widely used collection. Most programmers learn ArrayList first after the array, and for most jobs they need nothing else. This section first gives the contract of the List interface. It then examines the two basic implementations, ArrayList and LinkedList, together with their internal structures. At the end of the section come Vector and Stack, left over from the first versions of Java, and the three ways of traversing a list.

5.2.1The List interface

Definition 5.3

A list is a collection that keeps elements in insertion order, provides access to each element by an index, and allows the same element to appear more than once. The index of the first element is 0, and that of the last is size() − 1.

The word "order" in the definition can mean two different things, and the two are often confused. The elements of a list are ordered: each element has a definite position and stays at that position. But a list is not sorted by itself. Numbers added in the order 30, 10, 20 remain 30, 10, 20 in the list. To arrange them from smallest to largest, a sorting algorithm must be called separately.

The List interface adds index-based methods to the methods inherited from Collection. Table 5.3 gives the most commonly used ones.

Table 5.3: The basic methods of the List<E> interface.
MethodPurpose
add(E e)appends at the end
add(int i, E e)inserts at position i; later elements shift one place right
get(int i)returns the element at i
set(int i, E e)replaces the element at i, returns the old one
remove(int i)removes and returns the element at i
remove(Object o)removes the first element equal to o
indexOf(Object o)the first position of o; −1 if absent
size()number of elements

The interface has three well-known implementations. ArrayList uses a dynamic array and is very fast at access by index. LinkedList uses a doubly linked list; insertion and removal at the ends of the list are fast. Vector is an old, synchronized version; in new code ArrayList is preferred in its place.

Common mistake

Confusing remove(int) with remove(Object). In a List<Integer>, both methods carry the same name. In the call list.remove(1), the argument is an int, and the compiler picks the matching remove(int index) without boxing: the element at index 1 is deleted. To delete the element whose value is 1, the argument is passed as an object: list.remove(Integer.valueOf(1)). Examples are run in the section on common mistakes.

5.2.2ArrayList and its internal array

Definition 5.4

A dynamic array is a structure that keeps its elements in an ordinary internal array and grows by copying into a larger array when that array becomes full. ArrayList implements the List interface with a dynamic array; it is derived from the AbstractList class.

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Pear");
System.out.println(fruits.get(1));  // by index
Pear

In this example the variable is deliberately declared with type ArrayList; the slides show both spellings. fruits.get(1) returns the element at index 1, that is, the second fruit added. Since indices start at 0, "Apple" is at 0 and "Pear" at 1.

The speed of ArrayList comes from its internal array. The get(i) call goes directly to cell number i of the array. Every cell in the array has the same size, and the cells lie one after another in memory. So the address of cell i is found with a single multiplication and addition. Whether the list has ten elements or ten million, this job takes the same time. set(i, e) is fast for the same reason.

Big O notation is used to describe costs. O(1) says that the time is independent of the number of elements, that is, constant. O(n) says that the time grows in proportion to the number of elements n: when the number of elements doubles, the time also roughly doubles. get and set are O(1). Appending at the end is O(1) on average. Insertion into the middle and removal from the middle are O(n) because they shift elements.

How does ArrayList grow?

The length of the internal array is called the capacity. Capacity is not the same thing as the size() of the list. size() is the number of filled cells; capacity is the total number of cells. As long as empty cells remain, the list appends directly. When the array is full, a larger array is allocated and the old elements are copied into it. Figure 5.4 shows this process on a list with capacity 4.

internal array (elements)A0B1C23size = 3, capacity = 4 internal array (elements)A0B1C2D3size = 4, capacity = 4 (full)
internal array (elements)A0B1C2D3new array: capacity 4 + 4/2 = 6A0B1C2D3454 elements copied internal array (elements)A0B1C2D3old array: no longer usednew array: capacity 4 + 4/2 = 6A0B1C2D3E45size = 5, capacity = 6
Figure 5.4: The growth of an ArrayList. At top left, the 4-cell internal array of a list created with new ArrayList<>(4) holds A, B, C. At top right, add("D") writes into the empty cell and no element is moved. At bottom left, when add("E") arrives the array is full: a new 6-cell array is allocated and the 4 old elements are copied one by one. At bottom right, E is written into cell 4 of the new array; the old array is left to the garbage collector.

The length of the new array is about 1.5 times the old capacity: 4 + 4/2 = 6. We can observe this rule ourselves. The internal array of ArrayList is in a private field called elementData. Normal programs do not access this field, but for measurement it can be read with reflection. The following output is the result of this note's measurement program on JDK 21:

size 3 cap 4
size 4 cap 4
size 5 cap 6
empty cap 0: 1->10 11->15 16->22 23->33 34->49 50->73 74->109
after clear cap 109

The first three lines are exactly the same as the steps in the figure: with capacity 4, three and four elements fit, and at the fifth element the capacity becomes 6. The fourth line shows the behavior of the no-argument new ArrayList<>(). An empty list allocates no cells at all at first (capacity 0). The first add allocates a 10-cell array; this is what "default capacity 10" in the slides means. Later growths go to 15, 22, 33, 49, 73, and 109 cells. Each is 1.5 times the previous one, with the fraction discarded. The last line shows an important detail: clear() deletes the elements but does not shrink the internal array. Deleting does not reduce the capacity.

Amortized O(1)

At the moment of growth, the add call copies all the elements; this single call takes O(n). Even so, appending at the end is said to be "O(1) on average". The reason is that copying is rare. Because the capacity grows by a factor of 1.5 each time, the number of additions between two growths also keeps increasing. Dividing the total number of copies by the n additions gives a constant number. This note's counting program computes it directly:

10 adds: 0 copies, ratio 0.00
100 adds: 202 copies, ratio 2.02
1000 adds: 2456 copies, ratio 2.46
1000000 adds: 2430972 copies, ratio 2.43

Over a million additions, about 2.4 million elements are copied. On average 2.43 copies fall on each addition, and this ratio does not increase as n grows. Whatever the number of additions, each addition does a constant amount of work on average. This kind of average is called amortized cost. A single call is sometimes expensive, but over a long sequence of calls the share of the expensive steps stays constant.

5.2.3Tracing ArrayList methods

To see how the list methods work together, let us build a list with five names and make changes to it:

ArrayList<String> names = new ArrayList<>();
names.add("Ali");
names.add("Banu");
names.add("Cem");
names.add("Deniz");
names.add("Ece");
System.out.println(names);
names.set(3, "Can");       // replace index 3
System.out.println(names);
names.remove(4);           // remove index 4
System.out.println(names);
names.add(2, "Fatma");     // insert at index 2
System.out.println(names);
int index = names.indexOf("Banu");
System.out.println("index: " + index);
boolean hasEce = names.contains("Ece");
System.out.println("has Ece: " + hasEce);
System.out.println("size: " + names.size());
[Ali, Banu, Cem, Deniz, Ece]
[Ali, Banu, Cem, Can, Ece]
[Ali, Banu, Cem, Can]
[Ali, Banu, Fatma, Cem, Can]
index: 1
has Ece: false
size: 5

Table 5.4 gives the contents of the list and the new output at each step. The line numbers are the lines of the code above.

Table 5.4: Tracing the ArrayList methods. The List column gives the elements at the end of the step, in index order.
StepLineListVariablesNew output
11: ArrayList<String> names = new ArrayList<>();empty——
22: names.add("Ali");Ali——
33: names.add("Banu");
4: names.add("Cem");
5: names.add("Deniz");
6: names.add("Ece");
Ali, Banu, Cem, Deniz, Ece——
47: System.out.println(names);Ali, Banu, Cem, Deniz, Ece—[Ali, Banu, Cem, Deniz, Ece]
58: names.set(3, "Can"); // replace index 3
9: System.out.println(names);
Ali, Banu, Cem, Can, Ece—[Ali, Banu, Cem, Can, Ece]
610: names.remove(4); // remove index 4
11: System.out.println(names);
Ali, Banu, Cem, Can—[Ali, Banu, Cem, Can]
712: names.add(2, "Fatma"); // insert at index 2
13: System.out.println(names);
Ali, Banu, Fatma, Cem, Can—[Ali, Banu, Fatma, Cem, Can]
814: int index = names.indexOf("Banu");
15: System.out.println("index: " + index);
Ali, Banu, Fatma, Cem, Canindex=1index: 1
916: boolean hasEce = names.contains("Ece");
17: System.out.println("has Ece: " + hasEce);
Ali, Banu, Fatma, Cem, Canindex=1, hasEce=falsehas Ece: false
1018: System.out.println("size: " + names.size());Ali, Banu, Fatma, Cem, Canindex=1, hasEce=falsesize: 5

In the first step an empty list is created; size() is 0. add("Ali") puts the first element at index 0. Four more add calls place the elements at indices 1, 2, 3, and 4. When the list is printed, the elements appear in insertion order. Figure 5.5 shows three important moments of the trace.

namessize = 5Ali0Banu1Cem2Can3Ece4 namessize = 4Ali0Banu1Cem2Can3 namessize = 5Ali0Banu1Fatma2Cem3Can4
Figure 5.5: Three moments of change. On the left, set(3, "Can"): Can is written in place of Deniz, and the size stays 5. In the middle, remove(4): the last element, Ece, is deleted and no shifting is needed. On the right, add(2, "Fatma"): Cem and Can shift one place right and Fatma goes to index 2.

set(3, "Can") does not change the size; only the content of cell 3 changes. The method returns the old value ("Deniz"), but the return value is not used in this example. remove(4) deletes the last element. Since there is no element behind the last one, nothing shifts and the operation takes O(1). add(2, "Fatma"), on the other hand, inserts into the middle of the list. First Cem and Can at indices 2 and 3 are moved one cell to the right, then Fatma is written into the freed cell 2.

The last three lines perform searches. indexOf("Banu") scans the list from the start and returns the index of the first match: 1. contains("Ece") does the same scan, but because Ece was deleted earlier the result is false. The final size is 5: 5 additions and 1 insertion were made, and 1 element was deleted. Both search methods are O(n) because in the worst case they traverse the whole list. If the question "is it there?" is asked often on a list, switching to a set is the right choice.

5.2.4Inserting into and deleting from the middle

To see the cost of shifting more closely, let us insert an element into the middle of a four-number list and delete an element from the front:

List<Integer> list2 = new ArrayList<>(Arrays.asList(10, 20, 30, 40));
list2.add(1, 15);      // insert: 20, 30, 40 shift right
System.out.println(list2);
list2.remove(0);       // remove first: all shift left
System.out.println(list2);
[10, 15, 20, 30, 40]
[15, 20, 30, 40]

The expression new ArrayList<>(Arrays.asList(10, 20, 30, 40)) creates a modifiable list filled with the given values. This pattern is often used in short examples. Figure 5.6 shows the two operations step by step.

1002013024034
10012023034043 elements right
100151202303404[10, 15, 20, 30, 40]
1001512023034044 elements left
150201302403[15, 20, 30, 40]
Figure 5.6: Insertion into the middle and removal from the front. Initially the list is [10, 20, 30, 40]. For add(1, 15), the elements after index 1 first shift one place right, starting from the end, and then 15 is written into the freed cell. remove(0) deletes 10; the four elements behind it shift one place left. The result is [15, 20, 30, 40].

The right shift starts from the end. First 40, then 30, then 20 move one cell to the right. Had it started from the front, 20 would overwrite 30 and 30 would be lost. In the four-element list, add(1, 15) moves three elements. In general, inserting at position i moves n − i elements. The worst case is insertion at the front; all n elements change places. The same holds for deletion: remove(0) pulls all the elements behind it one place to the left.

5.2.5LinkedList

Definition 5.5

A doubly linked list is a structure that stores its elements in nodes. Each node holds a value and references to the previous (prev) and next (next) nodes. LinkedList uses this structure; it is derived from the AbstractSequentialList class and implements both the List and the Deque interface.

CherryprevnextAppleprevnextPearprevnextBananaprevnextnullnullfirstlast
Figure 5.7: A doubly linked list: Cherry, Apple, Pear, Banana. first points to the first node and last to the last node. The next arrow of each node goes to the next node and the prev arrow to the previous node; the arrows at the ends are null.

In LinkedList there is no concept of capacity. Each addition creates a new node and links it to its neighbors. No element is shifted. That is why insertion and removal at the ends of the list are O(1): the first and last references keep the ends at hand, and only a few references change.

The price is paid in access by index. The nodes do not lie one after another in memory; each can be anywhere in the heap. To find element number 3, you must start from the front and follow the next links one by one. So get(i) is O(n). Java's implementation makes a small improvement: if the index is in the first half of the list it walks from the front, and if it is in the second half it walks from the back. This reduces the walk to at most n/2 steps, but the growth rate is still O(n).

The analogy in the slides explains this trade-off well. A linked list is like a row of people holding hands. If someone is to step in between, only two people change hands. But to find the 3rd person, you must count from the start.

LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Pear");
fruits.addFirst("Cherry");   // add to front
fruits.addLast("Banana");      // add to end
System.out.println(fruits);
System.out.println(fruits.getFirst());
System.out.println(fruits.getLast());
fruits.removeFirst();
System.out.println(fruits);
[Cherry, Apple, Pear, Banana]
Cherry
Banana
[Apple, Pear, Banana]

The methods addFirst, addLast, getFirst, getLast, removeFirst, and removeLast in this example come from the Deque interface. add, get, and remove(i) come from List. Because the variable is declared with type LinkedList, the methods of both interfaces can be used.

Tracing the nodes step by step

Table 5.5 traces the same program line by line. The Nodes column shows the order the list gives when traversed from first along the next links.

Table 5.5: Tracing the LinkedList operations.
StepLineNodes (front to back)New output
11: LinkedList<String> fruits = new LinkedList<>();first = last = null—
22: fruits.add("Apple");[Apple]—
33: fruits.add("Pear");[Apple, Pear]—
44: fruits.addFirst("Cherry");[Cherry, Apple, Pear]—
55: fruits.addLast("Banana");[Cherry, Apple, Pear, Banana]—
66: System.out.println(fruits);[Cherry, Apple, Pear, Banana][Cherry, Apple, Pear, Banana]
77: System.out.println(fruits.getFirst());[Cherry, Apple, Pear, Banana]Cherry
88: System.out.println(fruits.getLast());[Cherry, Apple, Pear, Banana]Banana
99: fruits.removeFirst();[Apple, Pear, Banana]—
1010: System.out.println(fruits);[Apple, Pear, Banana][Apple, Pear, Banana]

Initially the list is empty: first and last are both null. For "Apple" the first node is created; since the single node is both first and last, both references point to it. When "Pear" is linked at the end, three references change. Apple's next points to Pear, Pear's prev points to Apple, and last moves to Pear. Figure 5.8 shows this linking and the effect of removeFirst.

ApplePearfirstlast CherryApplePearfirstlast
CherryApplePearBananafirstlast CherryApplePearBananafirstlastdetached
Figure 5.8: Four moments in the linked list. At top left, Pear is linked at the end. At top right, addFirst("Cherry") adds the new node at the front; Apple's prev and first change. At bottom left, addLast("Banana"). At bottom right, removeFirst(): first moves to Apple, Apple's prev becomes null, and the Cherry node is cut off from the list.

In the addFirst("Cherry") call, the new node's next points to Apple, Apple's prev points to Cherry, and first moves to Cherry. In an array, insertion at the front would shift all the elements. Here only three references changed. addLast("Banana") does the same job at the end. println prints the list by starting from first and following the next links.

getFirst() and getLast() return directly the value of the node that first and last point to; both are O(1). removeFirst() moves first to the next node and sets that node's prev to null. Since no reference to the Cherry node remains, the garbage collector cleans it up later.

On an empty LinkedList, peekFirst() returns null, while getFirst() throws a NoSuchElementException.

5.2.6ArrayList or LinkedList?

The two classes implement the same List interface, but the costs of their operations are very different. Table 5.6 compares the basic operations.

Table 5.6: The costs of ArrayList and LinkedList operations.
OperationArrayListLinkedList
get(i), set(i, e)O(1)O(n): walks node by node
Append at the end add(e)O(1) on average (occasional copying)O(1)
Insert at front / remove from frontO(n): all elements shiftO(1)
Insert into / remove from the middleO(n): shiftingO(n): finding the position + O(1) linking
Memory uselow: only the arrayhigh: 2 extra references per node

The fourth row of the table is often misunderstood. People say "insertion into the middle of a linked list is O(1)", but this holds only if the right node is already in hand. The call add(i, e) first walks to find node number i; that walk is O(n). The linking step is O(1). In the end, insertion into the middle is O(n) in both structures. The difference is that ArrayList shifts elements while LinkedList counts nodes. Shifting an array that lies contiguously in memory is often faster than walking across scattered nodes.

To see how large the difference is, let us measure two extreme cases. The measurement program inserts 100,000 elements at the front of each list, then calls get(i) 100,000 times:

insert at front ms: ArrayList 539, LinkedList 1 | get(i) ms: ArrayList 0, LinkedList 5161

The times vary with the machine and the run; these numbers come from a run on the computer on which this note was written. The ratios, however, are stable. For insertion at the front, LinkedList is hundreds of times faster, because ArrayList shifts all the elements on every insertion and the total work grows to O(n²). For reading by index the situation reverses: ArrayList finishes in under a millisecond, while LinkedList spends seconds because it walks node by node for every get.

In most cases the right choice is ArrayList. Programs mostly fill a list by appending at the end and read it by index or with for-each. For these two jobs ArrayList is at least as fast as LinkedList and uses less memory. If insertions and removals are frequent and especially at the ends of the list, LinkedList can be considered. For queue and stack needs, however, ArrayDeque is usually a better choice.

Common mistake

Traversing a LinkedList with an indexed for loop. In the loop for (int i = 0; i < l.size(); i++) l.get(i), every get(i) walks from the front or the back. In a list of n elements the total work becomes O(n²), and as the measurement showed, it takes seconds on large lists. A linked list is traversed with for-each or an iterator; these ways move on to the next node at each step, and the total work is O(n).

5.2.7Vector and Stack

Vector and Stack are left over from Java 1.0; when the Collections Framework arrived with Java 1.2, these two classes were adapted to the List interface. They are still seen in old code and in some textbooks. For this reason you need to know how they work, but in new code more suitable classes are used in their place.

Vector

Vector is an expandable dynamic array that implements the List interface. It starts with the specified capacity, or with 10 cells if none is specified. When full, its capacity doubles; this is its difference from the 1.5-fold growth of ArrayList. The main distinction, however, is that its methods are synchronized. Every time a method is called, the object is locked. In this way several threads can access the same list at the same time safely. But the lock is acquired and released on every call even in single-threaded programs, and this wastes time for nothing.

Vector<Integer> v = new Vector<>();   // capacity: 10
for (int i = 1; i <= 11; i++) {
    v.addElement(i * 10);
}
System.out.println(v.size() + " / " + v.capacity());
System.out.println(v.elementAt(0));
v.removeElement(110);    // value 110
System.out.println(v.size() + " / " + v.capacity());
11 / 20
10
10 / 20

The values 10, 20, …, 110 are added. When the eleventh element arrives, the 10-cell array is full and the capacity doubles to 20. elementAt(0) returns the first element. removeElement(110) deletes the element whose value is 110; the size falls to 10, but the capacity stays at 20. Deletion does not shrink the capacity. Table 5.7 gives the old-style methods specific to Vector. All of these methods have an equivalent in List: add instead of addElement, get instead of elementAt.

Table 5.7: Methods specific to Vector.
MethodPurpose
addElement(E obj)adds an element
elementAt(int i)returns the element at i
removeElement(Object obj)removes the element
size()number of elements
capacity()current capacity

Stack

Definition 5.6

A stack is a structure that works on the last-in, first-out (LIFO) principle. The most recently added element sits at the top, and the oldest at the base. Insertion and removal are done only at the top.

In everyday life a stack is like plates piled on top of each other: a plate is always put on top and taken from the top. In programming a stack has many uses. Undo in a text editor reverses the most recent action first. Whether the parentheses in an expression are balanced is checked with a stack. Depth-first search keeps the nodes to be visited on a stack. Method calls are also stored on the call stack.

Java's Stack class is derived from Vector. Table 5.8 gives its methods and Figure 5.9 its basic operation.

Table 5.8: The methods of the Stack class.
MethodPurpose
push(E item)adds to the top
pop()removes and returns the top element
peek()returns the top element without removing it
empty()is the stack empty?
search(Object o)position counted from the top starting at 1; −1 if absent
CBAtopbasepush(C)pop() → C
Figure 5.9: The stack. push(C) puts C on top; pop() removes and returns the top element C. A stays at the bottom (the base).
Stack<String> stack = new Stack<>();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack);
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.search("A"));
System.out.println(stack.empty());
[A, B, C]
C
C
2
false

Table 5.9 traces the program step by step. The Stack column gives the elements from bottom to top.

Table 5.9: Tracing the Stack operations.
StepLineVariablesNew output
11: Stack<String> stack = new Stack<>();stack=[]—
22: stack.push("A");stack=[A]—
33: stack.push("B");stack=[A, B]—
44: stack.push("C");stack=[A, B, C]—
55: System.out.println(stack);stack=[A, B, C][A, B, C]
66: System.out.println(stack.peek());stack=[A, B, C]C
77: System.out.println(stack.pop());stack=[A, B]C
88: System.out.println(stack.search("A"));stack=[A, B]2
99: System.out.println(stack.empty());stack=[A, B]false

After three push calls, A is at the bottom and C at the top. println prints the stack from bottom to top: [A, B, C]. This order may surprise at first, because the "top" is at the right end. Since Stack is a Vector, it keeps its elements in the internal array in insertion order, and the top is the last cell of the array. peek() returns C but does not remove it. pop() removes and returns C; the last one in has come out first. search("A") counts the position from the top starting at 1: B is 1, A is 2. This count differs from indices: it starts at 1, not 0. On the last line the stack holds two elements, and empty() returns false.

Since push, pop, and peek work at the end of the internal array, all three are O(1) (push amortized). If pop() or peek() is called on an empty stack, an EmptyStackException is thrown:

Exception in thread "main" java.util.EmptyStackException

In modern code, ArrayDeque (or LinkedList), which implements the Deque interface, is recommended in place of Stack. Stack has two problems. The first is the unnecessary synchronization inherited from Vector. The second is the extra methods that inheritance brings. Since Stack is a Vector, calls such as add(0, x) or remove(1) can also be made. These break the "access only from the top" rule of the stack.

5.2.8Traversing a list

There are three common ways to process all the elements of a list in order:

List<String> courses = new ArrayList<>(
        Arrays.asList("Physics", "Java", "Circuits"));
// 1) indexed for
for (int i = 0; i < courses.size(); i++) {
    System.out.print(courses.get(i) + " ");
}
System.out.println();
// 2) enhanced for (for-each)
for (String d : courses) {
    System.out.print(d + " ");
}
System.out.println();
// 3) forEach + lambda (Java 8+)
courses.forEach(d -> System.out.print(d + " "));
System.out.println();
Physics Java Circuits 
Physics Java Circuits 
Physics Java Circuits 

The first way is the indexed for loop. The loop variable i runs from 0 to size() − 1 and each element is obtained with get(i). This way is used when the index itself is needed, for example to print "Java is in 3rd place". It works only on lists, because sets and queues have no get(i).

The second way is the enhanced for, that is, the for-each loop. It is the most readable form and works on every collection that is Iterable. The compiler turns this loop into an iterator behind the scenes. This transformation is traced in detail in the iterator section.

The third way is the forEach method and a lambda expression (Java 8+). The expression d -> System.out.print(d + " ") means "for each element d, do this". It is a short form, but it cannot modify local variables outside the loop body. If you try to increment a counter from inside the lambda, the compiler stops:

LambdaOutside.java:6: error: local variables referenced from a lambda expression must be final or effectively final
        l.forEach(x -> total += x);
                       ^
1 error

A lambda can only read local variables from outside; those variables must be final or effectively final (assigned once and never changed). For accumulating values such as a total, either for-each is used or stream operations such as sum and reduce.

The output of the three ways is the same. If you need to remove elements from the list while traversing, none of the three is suitable. For this job the iterator's own remove method is used.

5.3Queues

A queue holds elements waiting to be processed. Documents sent to a printer, requests arriving at a server, and moves waiting their turn in a game all wait in a queue. The real question of a queue is "who is next?" The answer depends on the structure: in an ordinary queue the first to arrive, in a priority queue the most urgent, and in a stack the most recent arrival is next. This section describes these three behaviors through Queue, PriorityQueue, and Deque, respectively.

5.3.1The Queue interface

Definition 5.7

A queue is a structure that works on the first-in, first-out (FIFO) principle. A new element enters at the end of the queue; the element to be processed is taken from the front of the queue. Elements leave in the order in which they were added.

A supermarket checkout is a useful analogy. You join the line at the back, and the person at the front pays. No one can enter or leave in the middle of the line. Figure 5.10 shows this arrangement.

AliBanuCemheadtailpoll()offer(e)
Figure 5.10: The queue. offer(e) adds at the tail, poll() removes the element at the head (Ali).

The Queue interface has three well-known implementations. LinkedList works with a doubly linked list and ArrayDeque with a dynamic array; both are true FIFO queues. PriorityQueue, on the other hand, removes elements by priority; therefore it is not FIFO. Typical uses of a queue are a print queue, a task queue, and breadth-first search.

Two forms of each operation

The Queue interface offers each basic operation in two forms. One form throws an exception on failure, the other returns a special value. Table 5.10 gives this pairing.

Table 5.10: The two forms of the Queue methods.
OperationThrows an exceptionReturns a special value
Insert (at the tail)add(e)offer(e) → false
Remove (from the head)remove()poll() → null
Examine (the head)element()peek() → null

When the queue is empty, remove() and element() throw NoSuchElementException, while poll() and peek() return null. On the insertion side, the difference appears only in queues with limited capacity. On a full queue, add throws an exception while offer returns false. Since LinkedList and ArrayDeque grow without limit, insertion always succeeds in these two. The difference in behavior on an empty queue is seen below:

import java.util.*;
public class EmptyQueue {
    public static void main(String[] args) {
        Queue<String> q = new LinkedList<>();
        System.out.println(q.poll() + " " + q.peek());
        try { q.element(); } catch (RuntimeException e) { System.out.println("element: " + e); }
        q.remove();
    }
}
null null
element: java.util.NoSuchElementException
Exception in thread "main" java.util.NoSuchElementException

Tracing a queue

Queue<String> queue = new LinkedList<>();
queue.offer("Ali");
queue.offer("Banu");
queue.offer("Cem");
System.out.println(queue);
System.out.println(queue.peek());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.size());
System.out.println(queue.poll());
System.out.println(queue.poll());
[Ali, Banu, Cem]
Ali
Ali
Banu
1
Cem
null

The variable has type Queue and the object is a LinkedList. In this way only queue methods can be used; a call that would break the queue discipline, such as queue.get(1), does not compile. Table 5.11 gives the contents of the queue at each step.

Table 5.11: Tracing the Queue operations. The Queue column gives the elements from head to tail.
StepLineQueue (head to tail)New output
11: Queue<String> queue = new LinkedList<>();empty—
22: queue.offer("Ali");Ali—
33: queue.offer("Banu");Ali, Banu—
44: queue.offer("Cem");Ali, Banu, Cem—
55: System.out.println(queue);Ali, Banu, Cem[Ali, Banu, Cem]
66: System.out.println(queue.peek());Ali, Banu, CemAli
77: System.out.println(queue.poll());Banu, CemAli
88: System.out.println(queue.poll());CemBanu
99: System.out.println(queue.size());Cem1
1010: System.out.println(queue.poll());emptyCem
1111: System.out.println(queue.poll());emptynull

Three offer calls add Ali, Banu, and Cem to the tail in order. peek() returns the head (Ali) but does not change the queue. The first poll() removes and returns Ali; the first one in has come out first. The second poll() removes Banu. At this point size() is 1. The third poll() removes Cem and the queue becomes empty. The fourth poll() does not raise an error; it returns null. Since the head and tail of the queue are found in constant time, offer, poll, and peek are O(1).

5.3.2PriorityQueue and the binary heap

Definition 5.8

A priority queue is a queue in which the element that leaves is always the highest-priority element; the order of insertion is not decisive. In PriorityQueue, the default priority is the natural order: the smallest element leaves first.

Typical uses of a priority queue are task scheduling, emergency-room order, and shortest-path algorithms. In an emergency room, patients are called not in order of arrival but according to the severity of their condition. The operating system also moves priority jobs to the front. The elements must be comparable. Either the element class implements the Comparable interface, or a Comparator is given to the queue. A comparator is also given for the reverse order, that is, for the largest to leave first. Table 5.12 lists the basic methods.

Table 5.12: PriorityQueue methods and their costs.
MethodPurposeCost
add(E e)adds an elementO(log n)
poll()removes and returns the highest-priority elementO(log n)
peek()returns the highest-priority element without removing itO(1)
remove(Object o)removes the specified elementO(n)
size()number of elementsO(1)

PriorityQueue internally uses a binary heap. This word "heap" shares its name with the memory heap, but it is a different structure. A binary heap is a complete binary tree stored in an array. The rule of the tree is this: every parent is less than or equal to its children. This rule holds only between parent and child; there is no order among siblings. As a consequence of the rule, the smallest element is always at the root.

The tree is stored in an array as follows. The root is at index 0. The children of the node at index i are at 2i + 1 and 2i + 2, and its parent is at (i − 1) / 2. In this way you can move up and down the tree without keeping any references. Figure 5.11 shows a four-element heap both as a tree and as an array.

10204030← peek / poll100201402303array 10[0]20[1]40[2]30[3]internal array:100201402303
Figure 5.11: The binary heap. On the left, the root is the smallest element; peek and poll use the root. On the right is the internal layout after 30, 10, 40, 20 are added: the array [10, 20, 40, 30]. In the tree, 10 is the root; 20 and 40 are its children, and 30 is the child of 20.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(10);
pq.add(40);
pq.add(20);
System.out.println(pq.peek());   // smallest
System.out.println(pq);          // heap order
while (!pq.isEmpty()) {
    System.out.print(pq.poll() + " ");
}
System.out.println();
10
[10, 20, 40, 30]
10 20 30 40 

The second line of the output often surprises. println(pq) does not print the elements in sorted order; it prints the internal array as it is. The internal array obeys only the rule "every parent is less than its children": 10 is less than its children 20 and 40, and 20 is less than its child 30. But there is no order between 40 and 30. For a sorted result, the elements are removed one by one with poll; the removal order is always from smallest to largest.

Tracing the heap rule step by step

Table 5.13 shows what each insertion and removal does internally. The Internal array column gives the array after each step; the values were verified with a version of the same program that prints the internal array at each step.

Table 5.13: Tracing the internal array of PriorityQueue.
StepLineInternal arrayVariablesNew output
11: PriorityQueue<Integer> pq = new PriorityQueue<>();[]——
22: pq.add(30);[30]——
33: pq.add(10);[10, 30]——
44: pq.add(40);[10, 30, 40]——
55: pq.add(20);[10, 20, 40, 30]——
66: System.out.println(pq.peek());[10, 20, 40, 30]—10
77: System.out.println(pq);[10, 20, 40, 30]—[10, 20, 40, 30]
89: System.out.print(pq.poll() + " ");[20, 30, 40]x=1010
99: System.out.print(pq.poll() + " ");[30, 40]x=2020
109: System.out.print(pq.poll() + " ");[40]x=3030
119: System.out.print(pq.poll() + " ");[]x=4040
1211: System.out.println();[]——

Insertion is always done at the end of the array, and then the new element sifts up as far as necessary. 30 enters the empty array and becomes the root. 10 is added at index 1. Its parent is 30 at index 0, and 10 is less than it; since the rule is broken, the two swap. The root is now 10. 40 enters at index 2; since it is greater than its parent 10, it stays in place. 20 enters at index 3. Its parent is 30 at index 1. Since 20 is smaller, they swap. 20 is now at index 1; since it is greater than its parent 10, it stops. Figure 5.12 shows these steps on the tree.

1030array10030123 10204030array100201402303 203040array2003014023removed: 10
Figure 5.12: Three moments in the binary heap. On the left, 10 has been added and has risen to the root by swapping with 30. In the middle, 20 has been added, swapped with 30, and stopped below 10. On the right, the first poll(): the root 10 is removed, the last element 30 comes to the root, and it sinks by swapping with its smaller child 20.

peek() looks only at the root and is O(1). Removal is done as follows. The root is removed, the last element of the array is moved to the root, and it sifts down as far as necessary. In the first poll(), 10 is removed and the last element 30 comes to the root. The children of 30 are 20 and 40; it swaps with the smaller one, 20. The array becomes [20, 30, 40]. In the second poll(), 20 is removed, 40 comes to the root and swaps with its smaller child 30: [30, 40]. Then 30 and 40 are removed in turn and the queue becomes empty. The removal order is 10 20 30 40.

Sifting up and sifting down follow only a single branch. The height of a complete binary tree with n elements is about log₂ n. That is why add and poll are O(log n). Even in a heap of a million elements, each operation makes at most about 20 comparisons. remove(Object o), however, first scans the array to find the element and is O(n).

Common mistake

Traversing a priority queue with for-each and expecting a sorted result. for (int x : pq) and println(pq) give the internal array in array order; the result is not sorted. To take the elements in priority order, the pattern while (!pq.isEmpty()) pq.poll() is used. This pattern empties the queue; if the queue is needed again afterwards, a copy is taken first.

5.3.3Defining the priority

Numbers and strings are already comparable; their natural order is defined. Objects of our own classes, on the other hand, can enter a priority queue only if an order is defined. The first way to do this is for the class to implement the Comparable interface:

class Task implements Comparable<Task> {
    String name;
    int priority;          // smaller = more urgent

    Task(String name, int priority) {
        this.name = name;
        this.priority = priority;
    }

    @Override
    public int compareTo(Task o) {
        return Integer.compare(priority, o.priority);
    }

    @Override
    public String toString() {
        return name + "(" + priority + ")";
    }
}
PriorityQueue<Task> tasks =
        new PriorityQueue<>();
tasks.add(new Task("Report", 3));
tasks.add(new Task("Outage", 1));
tasks.add(new Task("Meeting", 2));
while (!tasks.isEmpty()) {
    System.out.println(tasks.poll());
}
Outage(1)
Meeting(2)
Report(3)

The Task class implements Comparable<Task> and writes a single method: compareTo. This method compares two tasks. It returns a negative number if this should come first, 0 if they are equal, and a positive number if it should come later. Integer.compare(priority, o.priority) does exactly this. Here a small priority number means urgent. Outage (1) leaves first, Meeting (2) next, and Report (3) last. The order of insertion plays no role at all.

If the reverse of the natural order is needed, there is no need to change the class. A comparator is passed to the queue's constructor. Collections.reverseOrder() is a ready-made comparator that reverses the natural order:

PriorityQueue<Integer> maxFirst =
        new PriorityQueue<>(
        Collections.reverseOrder());
maxFirst.add(30);
maxFirst.add(10);
maxFirst.add(40);
System.out.println(maxFirst.poll());
40

In this queue the largest element is at the root and leaves first. Comparators are treated in detail in the section on algorithms.

If the element class neither implements Comparable nor a comparator is given to the queue, the program compiles but a ClassCastException is thrown on the first insertion.

5.3.4Deque and ArrayDeque

Definition 5.9

A double-ended queue (Deque, pronounced "deck") is a queue in which elements can be added and removed from both the front and the back. It combines the functions of a queue (FIFO) and a stack (LIFO) in a single structure.

1510front (first)back (last)addFirst / offerFirstremoveFirst / pollFirstaddLast / offerLastremoveLast / pollLast
Figure 5.13: The double-ended queue. At the front, addFirst/offerFirst insert and removeFirst/pollFirst remove; at the back, addLast/offerLast and removeLast/pollLast do the same jobs.

The Deque interface has two implementations: LinkedList (a doubly linked list) and ArrayDeque (a dynamic array). There are the same three operations for both ends: insert, remove, and examine. Table 5.14 collects these methods. As in Queue, each operation has two forms, one that throws an exception and one that returns a special value. remove… and get… throw an exception on an empty deque; poll… and peek… return null.

Table 5.14: The Deque methods. The forms in parentheses return null instead of throwing an exception on an empty deque.
OperationAt the frontAt the back
InsertaddFirst(e) (offerFirst)addLast(e) (offerLast)
Remove and returnremoveFirst() (pollFirst)removeLast() (pollLast)
Return, do not removegetFirst() (peekFirst)getLast() (peekLast)

Deque also carries the familiar names of the stack and queue interfaces. The stack operations work at the front: push = addFirst, pop = removeFirst, peek = peekFirst. Among the queue operations, offer adds at the back (offerLast) and poll takes from the front (pollFirst). If you keep these correspondences in mind, the contents of a deque are easy to trace.

ArrayDeque

ArrayDeque implements the double-ended queue with a circular array. The array keeps two indices: the head (head) and the tail (tail). Adding at the front moves the head index back by one, and adding at the back moves the tail index forward by one. If an index runs off one end of the array, it wraps around to the other end. In this way, insertion and removal at both ends are O(1) with no shifting of elements. When the array is full, it is copied into a larger array, just as in ArrayList. Figure 5.14 shows this arrangement.

100123451657head ▲▲ tailwraps from the end to the start
Figure 5.14: The circular array of ArrayDeque. The head index is at 6, and the last element is at index 0. Reading from head to tail visits cells 6 and 7 and then, wrapping around to the start, cell 0: the deque is 1, 5, 10.

In most cases ArrayDeque is both faster and lighter than Stack and LinkedList. Unlike Stack, it does not acquire a lock on every call. Unlike LinkedList, it does not create a separate node object for each element. For this reason the Java documentation recommends ArrayDeque for stack and queue needs. Its only restriction is that it does not accept null elements. Because poll returns null on an empty deque, a null element would be confused with this return value; the class therefore rejects null from the start:

import java.util.*;
public class NullDeque {
    public static void main(String[] args) {
        Deque<String> d = new ArrayDeque<>();
        d.offer(null);
    }
}
Exception in thread "main" java.lang.NullPointerException

To use it as a stack, the variable is declared with type Deque:

Deque<String> stack = new ArrayDeque<>();
stack.push("A");     // adds at the front
stack.push("B");
System.out.println(stack.pop());
B

A and B are pushed to the front; B is on top and pop() returns it. Stack prints from bottom to top; ArrayDeque prints from front to back, that is, from top to bottom: after the same pushes of A, B, C, one gives [A, B, C] and the other [C, B, A].

Tracing an ArrayDeque

ArrayDeque<Integer> numbers = new ArrayDeque<>();
numbers.addFirst(5);
numbers.addLast(10);
numbers.addFirst(1);
System.out.println(numbers);
int firstNum = numbers.pollFirst();
int lastNum = numbers.pollLast();
System.out.println(firstNum + " " + lastNum);
System.out.println(numbers.peekFirst());
[1, 5, 10]
1 10
5

Table 5.15 traces the program step by step.

Table 5.15: Tracing the ArrayDeque operations. The Deque column gives the elements from front to back.
StepLineDeque (front to back)VariablesNew output
11: ArrayDeque<Integer> numbers = new ArrayDeque<>();empty——
22: numbers.addFirst(5);5——
33: numbers.addLast(10);5, 10——
44: numbers.addFirst(1);1, 5, 10——
55: System.out.println(numbers);1, 5, 10—[1, 5, 10]
66: int firstNum = numbers.pollFirst();5, 10firstNum=1—
77: int lastNum = numbers.pollLast();5firstNum=1, lastNum=10—
88: System.out.println(firstNum + " " + lastNum);5firstNum=1, lastNum=101 10
99: System.out.println(numbers.peekFirst());5firstNum=1, lastNum=105

addFirst(5) adds the single element; 5 is both the front and the back. addLast(10) adds 10 at the back. addFirst(1) adds 1 at the front; 5 and 10 stay where they are, and no element shifts. The deque is printed from front to back as [1, 5, 10]. pollFirst() removes the 1 at the front. The method returns an Integer; when it is assigned to int firstNum, automatic unboxing takes place. pollLast() removes the 10 at the back. Two values are printed: 1 10. Finally, peekFirst() returns the 5 at the front but does not remove it.

This program has a subtle trap. pollFirst() returns null on an empty deque. If the result is assigned directly to an int, unboxing is performed on null and the program crashes:

import java.util.*;
public class EmptyDeque {
    public static void main(String[] args) {
        ArrayDeque<Integer> d = new ArrayDeque<>();
        int x = d.pollFirst();
    }
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.ArrayDeque.pollFirst()" is null

The safety of the "special value" form is lost here. When using the poll family, the return value is first received as an Integer and checked for null, or isEmpty() is asked before the call.

5.4Sets

The course codes a student has taken, the distinct words in a text, the visited nodes in a network: what these have in common is that repetition is meaningless. The same course is not taken twice, and the same word does not increase the number of distinct words. The set is designed for this kind of data. The real strength of a set is that it answers the question "is this element present?" very quickly. This section covers the contract of the set, how the hash table works, the equals and hashCode rules needed for our own classes to behave correctly in a set, and the sorted set.

5.4.1The Set interface

Definition 5.10

A set is a collection that does not allow duplicate elements. It corresponds to the notion of a set in mathematics: only one of each element is present. When an attempt is made to add an element that already exists, add does not add it and returns false.

The Set interface in general gives no ordering guarantee; the traversal order depends on the implementation. The three implementations offer three different orders. HashSet is unordered. LinkedHashSet preserves insertion order. TreeSet keeps the elements sorted; the order is the natural order or a given Comparator. Set adds no new methods to Collection; it implements the same methods with the "no duplicates" rule.

Set<String> fruits = new HashSet<>();
System.out.println(fruits.add("Apple"));
System.out.println(fruits.add("Pear"));
System.out.println(fruits.add("Apple"));
System.out.println(fruits.size());
System.out.println(fruits.contains("Pear"));
fruits.remove("Pear");
System.out.println(fruits);
true
true
false
2
true
[Apple]

The first two add calls return true because they add new elements. The third, add("Apple"), tries to add an existing element; the set does not change and the result is false. That is why size() is 2, not 3. contains("Pear") returns true. After Pear is removed, only Apple remains in the set. The return value of add is useful in practice, too: the question "have we seen this word before?" is answered with a single add, without a separate contains call.

5.4.2HashSet and the hash table

Definition 5.11

A hash table is a structure that distributes elements into cells called buckets. The hashCode() method of each element produces an integer; a bucket number is computed from this integer, and the element goes directly to that bucket. Insertion and lookup take O(1) on average.

HashSet stores unique elements without order. It is derived from AbstractSet and implements the Set interface. Internally it actually uses a HashMap: the elements of the set are the keys of the map. To search for an element, there is no need to scan from start to finish as in a list. The element's bucket is computed and only that bucket is examined.

The bucket number is found in two steps. First the element's hashCode() value is taken. Java mixes the upper 16 bits of this value with its lower 16 bits: h ^ (h >>> 16). Then the last bits of the result become the bucket number. In a table with 16 buckets, the last 4 bits are used: (h ^ (h >>> 16)) & 15. This note's measurement program computes the buckets of four words with this formula:

salt hashCode=3522646 bucket=3
egg hashCode=100357 bucket=4
milk hashCode=3351579 bucket=8
coffee hashCode=-1355030580 bucket=7
Zeynep hashCode=-1621354421 bucket=7
Ahmet hashCode=63235125 bucket=1
Mert hashCode=2394618 bucket=14
Apple hashCode=63476538 bucket=2
Pear hashCode=2483462 bucket=3

The first four lines confirm the bucket numbers in the slides: salt 3, egg 4, milk 8, coffee 7. The same formula will also be used in the phone-book example in the section on maps. Figure 5.15 shows how these elements are placed in the table.

012salt3456789101112131415buckets: 0 … 15"salt".hashCode() = 3522646 → bucket 3
012salt3egg4567milk89101112131415buckets: 0 … 15"egg".hashCode() = 100357 → bucket 4already present → not added
012salt3egg456coffee7milk89101112131415buckets: 0 … 15"coffee".hashCode() = -1355030580 → bucket 7
Figure 5.15: A HashSet with 16 buckets. At the top, add("salt"): bucket 3 is computed from the hash value. In the middle, the second add("egg"): bucket 4 already holds an element equal under equals, so the element is not added and add returns false. At the bottom, add("coffee") is placed in bucket 7; traversal follows the order of the buckets: [salt, egg, coffee, milk].

The second add("egg") call shows how the "no duplicates" rule of the set is enforced. The element's bucket is computed: 4. It is compared with the elements in that bucket using equals. Since an equal element is found, no insertion is made. The whole set is not scanned; only a single bucket is examined.

The traversal order is the order of the buckets. The table is scanned from 0 to 15 and the elements in the filled buckets are given in turn. For this reason the order of a HashSet has nothing to do with insertion order. If the number of buckets changes, the order may change too. No program should rely on this order.

Two different elements can end up with the same bucket number; this is called a collision. For example, in the output above, coffee and Zeynep both have bucket 7. Colliding elements form a small chain in the same bucket, and the search in that chain is done with equals. Since Java 8, if the chain in a bucket grows too long (more than 8 elements and the table large enough), the chain is converted into a balanced tree. When the number of elements in the table exceeds 75% of the number of buckets (load factor 0.75), the table doubles in size and the elements are redistributed into new buckets. In this way the chains stay short and the average cost is O(1).

5.4.3LinkedHashSet and the order of the three sets

LinkedHashSet is derived from HashSet and additionally links its elements together with a linked list. The hash table provides fast access and uniqueness, while the linked list preserves insertion order. If both speed and order matter, LinkedHashSet is chosen. If order does not matter and speed is critical, HashSet is enough. Its basic methods are the same: add, remove, contains, size, clear.

LinkedHashSet<Integer> numbers =
        new LinkedHashSet<>();
numbers.add(5);
numbers.add(10);
numbers.add(5);   // duplicate: not added
numbers.add(1);
System.out.println(numbers);
[5, 10, 1]

The second add(5) is not added because it is a duplicate. The following 1 is linked at the end of the list. The output is the insertion order: first 5, then 10, then 1. The difference is clearly visible when the same words are added to all three sets:

String[] words = {"salt", "egg", "milk", "egg", "coffee"};
Set<String> h = new HashSet<>();
Set<String> l = new LinkedHashSet<>();
Set<String> t = new TreeSet<>();
for (String k : words) {
    h.add(k);
    l.add(k);
    t.add(k);
}
System.out.println("HashSet:       " + h);
System.out.println("LinkedHashSet: " + l);
System.out.println("TreeSet:       " + t);
HashSet:       [salt, egg, coffee, milk]
LinkedHashSet: [salt, egg, milk, coffee]
TreeSet:       [coffee, egg, milk, salt]

One of the five words is a repeat (the second "egg"); all three sets have four elements. HashSet gives the order of the buckets: salt 3, egg 4, coffee 7, milk 8. LinkedHashSet preserves insertion order. TreeSet gives alphabetical order. Table 5.16 compares the three classes.

Table 5.16: A comparison of the three set classes.
ClassTraversal orderUnderlying structureadd / contains
HashSetno guarantee (bucket order)hash tableO(1) average
LinkedHashSetinsertion orderhash table + linked listO(1) average
TreeSetsorted (ascending)red-black treeO(log n)

5.4.4Our own classes: equals and hashCode

Sets of strings and numbers work as expected, because the String and Integer classes write the equals and hashCode methods by value. If these methods are not written in our own classes, the versions inherited from Object are used. The equals of Object checks whether two references point to the same object. Two separate objects with the same field values are therefore counted as "different".

class Point {
    int x, y;
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Point)) return false;
        Point n = (Point) o;
        return x == n.x && y == n.y;
    }
    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}
Set<PointA> s1 = new HashSet<>();
s1.add(new PointA(1, 2));
s1.add(new PointA(1, 2));
System.out.println(s1.size());

Set<Point> s2 = new HashSet<>();
s2.add(new Point(1, 2));
s2.add(new Point(1, 2));
System.out.println(s2.size());
2
1

PointA is the same two-field class, but equals and hashCode are not written. When new PointA(1, 2) is executed twice, two separate objects are created in memory. The equals of Object counts them as different, and the set size is 2. In the Point class, on the other hand, both methods are overridden. equals compares the fields. hashCode produces a number from the same fields with Objects.hash(x, y). The same point enters the set once and the size is 1.

Definition 5.12

The equals–hashCode contract: if a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true. The converse is not required: two objects with equal hash codes can be different (a collision). Therefore every class that overrides equals also overrides hashCode, and both are computed from the same fields.

The reason for the rule lies in the way the hash table works. First the bucket is found with hashCode, then the elements in that bucket are compared with equals. If two equal objects have different hash codes, they go to different buckets. equals is never called and both enter the set. A class that writes only equals and forgets hashCode makes exactly this mistake:

// only equals written, hashCode forgotten
class PointE {
    int x, y;
    PointE(int x, int y) { this.x = x; this.y = y; }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof PointE)) return false;
        PointE n = (PointE) o;
        return x == n.x && y == n.y;
    }
}
import java.util.*;
public class EqualsOnly {
    public static void main(String[] args) {
        PointE a = new PointE(1, 2), b = new PointE(1, 2);
        Set<PointE> s = new HashSet<>();
        s.add(a);
        s.add(b);
        System.out.println(a.equals(b) + " " + s.size() + " " + s.contains(new PointE(1, 2)));
        List<PointE> l = new ArrayList<>();
        l.add(a);
        System.out.println(l.contains(new PointE(1, 2)));
    }
}
true 2 false
true

The first line shows the contradiction: a.equals(b) is true, yet the set holds two elements. A contains with a new PointE(1, 2) also returns false, because the new object's hash code (and therefore its bucket) is different. On the second line, the same object is searched for in a list and found. ArrayList.contains uses only equals; it does not look at the hash code. The same class works correctly in a list and incorrectly in a set. The compiler notices this situation and, when compiled with the -Xlint option, gives a warning: Class PointE overrides equals, but neither it nor any superclass overrides hashCode method.

The number produced by Objects.hash(x, y) comes from a simple formula: 31 · (31 · 1 + x) + y. For the point (1, 2) this gives 31 · 32 + 2 = 994. This number will be used in the next example.

5.4.5Modifying an object in a set

Even when equals and hashCode are written correctly, there is one more trap. What happens if a field that determines the hash code is changed after the object has entered the set? The following program tries this:

Set<Point> set = new HashSet<>();
Point p = new Point(1, 2);
set.add(p);
System.out.println(set.contains(p));
p.x = 5;              // field changed
System.out.println(set.contains(p));
System.out.println(set.contains(new Point(1, 2)));
set.add(p);
System.out.println(set.size());
true
false
false
2

Table 5.17 traces the program step by step. In the Variables column, hash is the current hash code of p, and bucket is the bucket number computed from this code.

Table 5.17: What happens when a field of an object in a set changes. The bucket number is the last 4 bits of the hash code (a table with 16 buckets).
StepLineVariablesNew output
11: Set<Point> set = new HashSet<>();——
22: Point p = new Point(1, 2);p=(1, 2), hash=994, bucket=2—
33: set.add(p);p=(1, 2), hash=994, bucket=2—
44: System.out.println(set.contains(p));p=(1, 2), hash=994, bucket=2true
55: p.x = 5; // field changedp=(5, 2), hash=1118, bucket=14—
66: System.out.println(set.contains(p));p=(5, 2), hash=1118, bucket=14false
77: System.out.println(set.contains(new Point(1, 2)));p=(5, 2), hash=1118, bucket=14, new=(1, 2)false
88: set.add(p);p=(5, 2), hash=1118, bucket=14—
99: System.out.println(set.size());p=(5, 2), hash=1118, bucket=142

Initially Objects.hash(1, 2) is 994. The binary representation of 994 is 1111100010, and its last 4 bits are 0010, that is, 2. add(p) puts the object into bucket 2. contains(p) again looks at bucket 2, equals returns true, and the result is true.

Then the assignment p.x = 5 is made. The object's hash code is now 31 · 36 + 2 = 1118 and its bucket is 14. But the object still sits in bucket 2; the set is unaware that the field has changed. Figure 5.16 shows this situation and its consequence.

buckets0123456789101112131415(1, 2)hash = 994 → bucket 2p buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p
buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p(1, 2) buckets0123456789101112131415(5, 2)hash = 1118 → bucket 14p
Figure 5.16: The lost element. At top left, p (1, 2) is placed in bucket 2. At top right, after p.x = 5 the hash is 1118 and the bucket 14; the object stays in bucket 2. At bottom left, new Point(1, 2) looks at bucket 2, but the object there is now (5, 2) and equals returns false. At bottom right, add(p) finds bucket 14 empty and adds the same object a second time.

The second contains(p) looks at bucket 14. It is empty and the result is false. The object is in the set, but cannot be found. In the third query, a new Point(1, 2) is searched for. This object's bucket is 2 and there really is an object there. But that object is now (5, 2); equals returns false and the result is again false. Finally, add(p) finds bucket 14 empty and adds the same object a second time. size() becomes 2. The set contains the same object twice; the "no duplicates" rule has been broken.

The lesson of this bug is that no exception is thrown. The program keeps running and produces a wrong result. The rule is simple: the fields that enter equals and hashCode of an object in a hashed collection (HashSet, the key of a HashMap) are not modified. Immutable objects such as String and Integer, or classes whose fields are final, are chosen as keys. If a field has to change, the object is first removed from the set, modified, and then added again.

5.4.6SortedSet and TreeSet

SortedSet is the set interface that stores its elements in sorted order. The order follows the natural order (Comparable) or a given Comparator. The interface offers new queries made possible by sortedness: the smallest and largest element, those smaller than a given value, and those within a given range. TreeSet is derived from AbstractSet and implements the NavigableSet (and hence SortedSet) interface. Internally it uses a red-black tree.

A red-black tree is a self-balancing binary search tree. The elements to the left of each node are smaller than it, those to the right are larger. During insertion and deletion, the tree rotates nodes so that its height stays on the order of log n. That is why insertion, deletion, and search are O(log n). It is slower than the O(1) of HashSet, but in return it gives order. Table 5.18 gives the sorted queries of TreeSet and Figure 5.17 the tree.

Table 5.18: The sorted-set methods of TreeSet.
MethodPurpose
first() / last()the smallest / the largest element
headSet(to)those smaller than to (to excluded)
tailSet(from)from and larger (from included)
subSet(from, to)from included, to excluded
comparator()the Comparator that orders the set; null for the natural order
add, removeinsertion, removal
7050906080headSet(70)= [50, 60]smaller → leftlarger → right
Figure 5.17: The tree inside a TreeSet (50, 60, 70, 80, 90). The root is 70; smaller elements are on the left, larger ones on the right. The green nodes show the range headSet(70) = [50, 60].
TreeSet<Integer> grades = new TreeSet<>();
grades.add(70);
grades.add(50);
grades.add(90);
grades.add(60);
grades.add(80);
System.out.println(grades);
System.out.println(grades.first() + " " + grades.last());
System.out.println(grades.headSet(70));     // 70 excluded
System.out.println(grades.tailSet(70));     // 70 included
System.out.println(grades.subSet(60, 90));  // [60, 90)
System.out.println(grades.comparator());    // natural order
TreeSet<String> fruits = new TreeSet<>();
fruits.add("Pear");
fruits.add("Apple");
System.out.println(fruits);
[50, 60, 70, 80, 90]
50 90
[50, 60]
[70, 80, 90]
[60, 70, 80]
null
[Apple, Pear]

The grades are added in the order 70, 50, 90, 60, 80, but the set is always printed sorted: [50, 60, 70, 80, 90]. first() is 50 and last() is 90. In the range methods it matters whether the bounds are included. The rule is "start included, end excluded"; this is consistent with other range methods of Java such as substring. headSet(70) does not include 70: [50, 60]. tailSet(70) includes 70: [70, 80, 90]. subSet(60, 90) is the mathematical interval [60, 90): [60, 70, 80]. Because the natural order is used, comparator() returns null. Strings are also sorted by character codes: "Apple" comes before "Pear".

5.4.7Set operations

Each of the mathematical operations of union, intersection, and difference has a counterpart in Collection. Table 5.19 gives the correspondence.

Table 5.19: Set operations and Java methods.
OperationMethod
union ∪addAll
intersection ∩retainAll
difference −removeAll
subset ⊆containsAll
Set<Integer> a = new TreeSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> b = new TreeSet<>(Arrays.asList(3, 4, 5));

Set<Integer> union = new TreeSet<>(a);
union.addAll(b);
Set<Integer> inter = new TreeSet<>(a);
inter.retainAll(b);
Set<Integer> diff = new TreeSet<>(a);
diff.removeAll(b);

System.out.println("A ∪ B = " + union);
System.out.println("A ∩ B = " + inter);
System.out.println("A − B = " + diff);
System.out.println(a.containsAll(inter));
A ∪ B = [1, 2, 3, 4, 5]
A ∩ B = [3, 4]
A − B = [1, 2]
true
AB12345A ∩ B
Figure 5.18: A Venn diagram. A = {1, 2, 3, 4}, B = {3, 4, 5}; the intersection is {3, 4}.

These methods modify the set on which they are called. Had a.addAll(b) been written, a itself would turn into the union and the original a would be lost in later operations. So a copy is made with new TreeSet<>(a) before each operation. The union adds the elements of b to the copy; the repeated 3 and 4 are not added a second time. The intersection leaves in the copy only the elements that are also in b. The difference removes the elements of b from the copy. The last line confirms that inter is a subset of a. Because TreeSet is used, the results are printed sorted. These operations perform a contains or add for each element of the collection given as a parameter; their cost is the number of elements times the cost of that operation.

5.5Maps

Getting from a student number to a student, from a product name to a price, from a word to its occurrence count is among the most frequent jobs in programming. In these jobs the data comes in pairs: a key and a value bound to it. A map stores these pairs and goes quickly from the key to the value. This section covers the map interface, its three basic implementations, and the old Hashtable class.

5.5.1The Map interface and its methods

Definition 5.13

A map is a structure that stores key-value pairs. Each key is mapped to one value. Keys are unique; values may repeat.

The best-known analogy for a map is the dictionary. A word (the key) leads to its meaning (the value), and the same word does not appear twice in a dictionary. Two different words, however, can have the same meaning. A map provides fast access by key and makes it possible to operate on pairs. Figure 5.19 shows the hierarchy of the map classes.

«interface»MapHashMapHashtable«interface»SortedMapLinkedHashMap«interface»NavigableMapTreeMap
Figure 5.19: The Map hierarchy. HashMap and Hashtable implement Map; LinkedHashMap extends HashMap. TreeMap implements NavigableMap, which extends SortedMap.

The three basic implementations are the map counterpart of the trio among the sets. HashMap gives no ordering guarantee. LinkedHashMap preserves insertion order. TreeMap keeps the keys sorted; the order is the natural order or a given Comparator. Table 5.20 gives the methods of the interface. K denotes the key type and V the value type. For example, Map<String, Integer> is a map from names to grades.

Table 5.20: The basic methods of the Map<K, V> interface.
MethodPurpose
put(K key, V value)maps the key to the value; if the key exists, replaces its value and returns the old one
get(Object key)returns the value of the key; null if the key is absent
remove(Object key)removes the key and its value
containsKey(Object key)is the key in the map?
containsValue(Object v)is the value in the map?
keySet()returns all keys as a Set
values()returns all values as a Collection
entrySet()returns all key-value pairs as a Set<Map.Entry<K, V>>
size(), isEmpty()number of pairs, is it empty?
getOrDefault(key, v)returns v if the key is absent (Java 8+)

5.5.2HashMap

HashMap stores key-value pairs in a hash table. It is derived from AbstractMap and implements Map. The bucket of a pair is computed from the hash code of the key; the hash code of the value is never used. That is why get and put are O(1) on average. The entries are stored without order.

HashMap<String, Double> prices = new HashMap<>();
prices.put("Tablet", 2000.0);
prices.put("Headphones", 350.0);
prices.put("Case", 120.0);
Double old = prices.put("Tablet", 1800.0);
System.out.println(old);
System.out.println(prices.get("Tablet"));
System.out.println(prices.get("Laptop"));
System.out.println(prices.containsKey("Case"));
prices.remove("Case");
System.out.println(prices.size());
prices.put(null, 0.0);         // a single null key
prices.put("Pen", null);     // null value
System.out.println(prices.size());
2000.0
1800.0
null
true
2
4
null true 0.0

The program proceeds as follows. Three products are added. The fourth call, put("Tablet", 1800.0), does not add a new pair; it changes the value of the existing key. This happens because keys are unique. put returns the old value: 2000.0. This return value is also a way to find out whether a key existed before; for a new key, put returns null. get("Tablet") gives the new value. get("Laptop") returns null for a key that is not present; it does not throw an exception. containsKey("Case") returns true. After Case is removed, two pairs remain in the map.

HashMap allows one null key and any number of null values. The extra lines add one null key and one null value; the size becomes 4. The last line, added in this note's program, shows the ambiguity this permission creates. get("Pen") returns null, but this does not mean "the key is absent"; containsKey("Pen") is true. In a map that stores null values, "absent" and "value is null" can be told apart only with containsKey. getOrDefault("Laptop", 0.0), on the other hand, returns the given default when the key is absent: 0.0.

Common mistake

Assigning the result of get directly to a primitive type. int n = counter.get(k); tries to unbox null if the key is absent and throws a NullPointerException (its message was given in the section on generic types). Where the key may be missing, getOrDefault(k, 0) is used, or containsKey is asked first.

5.5.3Traversing a map

Map is not Iterable; it cannot be given directly to a for-each loop. Traversal is done through one of the three views a map offers:

Map<String, Integer> grades = new TreeMap<>();
grades.put("Cem", 72);
grades.put("Ayse", 95);
grades.put("Banu", 60);

for (String name : grades.keySet()) {
    System.out.print(name + " ");
}
System.out.println();
for (Integer g : grades.values()) {
    System.out.print(g + " ");
}
System.out.println();
for (Map.Entry<String, Integer> g : grades.entrySet()) {
    System.out.println(g.getKey() + " → " + g.getValue());
}
Ayse Banu Cem 
95 60 72 
Ayse → 95
Banu → 60
Cem → 72

Here the object is a TreeMap; the keys come in alphabetical order. keySet() gives only the keys: Ayse Banu Cem. values() gives only the values, in the order of the keys: 95 60 72. entrySet() gives each pair as a Map.Entry object. getKey() reads the key and getValue() the value.

If both key and value are needed, the most efficient way is entrySet(). Traversing keySet() and calling get for each key gives the same result, but looks up the key again at every step. In a HashMap this extra lookup is O(1) on average; in a TreeMap, each get is O(log n) and the total work grows to O(n log n). entrySet, on the other hand, already holds the pairs, and the traversal is O(n).

Giving the map itself to for-each is a compile error:

MapForEach.java:5: error: for-each not applicable to expression type
        for (String s : m) {
                        ^
  required: array or java.lang.Iterable
  found:    Map<String,Integer>
1 error

The message says that for-each can be used only on arrays and java.lang.Iterable types, but a Map<String,Integer> was found.

5.5.4Counting words

The classic use of a map is counting the words in a text. Each word is a key, and the value is how many times that word occurs:

String text = "egg coffee egg milk coffee egg";
Map<String, Integer> counter = new TreeMap<>();
for (String k : text.split(" ")) {
    if (counter.containsKey(k)) {
        counter.put(k, counter.get(k) + 1);
    } else {
        counter.put(k, 1);
    }
}
System.out.println(counter);
{coffee=2, egg=3, milk=1}

text.split(" ") splits the text at spaces and gives an array of six words. The loop handles one of two cases for each word. If the word has been seen before, the old count is taken, increased by one, and written back. If it is seen for the first time, it is added with the value 1. Table 5.21 gives the state after each word.

Table 5.21: Tracing the word-counting program. The counter column is the map at the end of the step.
StepLinecounterVariablesNew output
11: String text = "egg coffee egg milk coffee egg";
2: Map<String, Integer> counter = new TreeMap<>();
empty——
23: for (String k : text.split(" ")) {
4: if (counter.containsKey(k)) {
7: counter.put(k, 1);
egg=1k="egg"—
33: for (String k : text.split(" ")) {
4: if (counter.containsKey(k)) {
7: counter.put(k, 1);
coffee=1, egg=1k="coffee"—
43: for (String k : text.split(" ")) {
4: if (counter.containsKey(k)) {
5: counter.put(k, counter.get(k) + 1);
coffee=1, egg=2k="egg"—
53: for (String k : text.split(" ")) {
4: if (counter.containsKey(k)) {
7: counter.put(k, 1);
coffee=1, egg=2, milk=1k="milk"—
63: for (String k : text.split(" ")) {
4: if (counter.containsKey(k)) {
5: counter.put(k, counter.get(k) + 1);
coffee=2, egg=2, milk=1k="coffee"—
73: for (String k : text.split(" ")) {
4: if (counter.containsKey(k)) {
5: counter.put(k, counter.get(k) + 1);
coffee=2, egg=3, milk=1k="egg"—
810: System.out.println(counter);coffee=2, egg=3, milk=1k="egg"{coffee=2, egg=3, milk=1}

"egg" and "coffee" are added with 1 when first seen. The third word is "egg" again. containsKey returns true; the old value 1 is taken and 2 is written. "milk" is added with 1. "coffee" rises to 2, and the last "egg" to 3. When the loop ends, the TreeMap prints the keys in alphabetical order. Figure 5.20 shows three moments of the map.

keyvalue"coffee"1"egg"1 keyvalue"coffee"1"egg"2 keyvalue"coffee"2"egg"3"milk"1
Figure 5.20: The word-counting map. On the left, after two words: coffee=1, egg=1. In the middle, after the second "egg": egg=2. On the right, at the end of the loop: coffee=2, egg=3, milk=1.

The loop body performs at most three map operations per word: containsKey, get, and put. With getOrDefault the same job shrinks to one line: counter.put(k, counter.getOrDefault(k, 0) + 1). The merge method, introduced in Java 8, is even shorter: counter.merge(k, 1, Integer::sum). If the key is absent this call writes 1; if present, it adds 1 to the old value. The three forms give the same result:

{coffee=2, egg=3, milk=1} {coffee=2, egg=3, milk=1}
{egg=3, milk=1, coffee=2}

The second line of the output is the same counts copied into a HashMap. The order is no longer alphabetical: egg, milk, coffee. The numbers are the same; only the traversal order has changed. If alphabetical output is wanted in word counting, TreeMap is chosen; if the fastest counting is wanted, HashMap. For a text of n words, counting takes O(n) on average with HashMap and O(n log n) with TreeMap.

5.5.5LinkedHashMap and Hashtable

LinkedHashMap

LinkedHashMap is a map derived from HashMap that additionally links its pairs together with a linked list. Thanks to this linked list, insertion order is preserved. It is preferred when speed and order matter together; if order does not matter, HashMap is enough. Its basic methods are the same as in Map: put, remove, get, containsKey, size. The difference in order is seen when the same phone book is put into three maps:

Map<String, String> contacts = new LinkedHashMap<>();
contacts.put("Zeynep", "555-1111");
contacts.put("Ahmet", "555-1234");
contacts.put("Mert", "555-2222");
Map<String, String> h = new HashMap<>(contacts);
Map<String, String> t = new TreeMap<>(contacts);
System.out.println("LinkedHashMap: " + contacts);
System.out.println("HashMap:       " + h);
System.out.println("TreeMap:       " + t);
LinkedHashMap: {Zeynep=555-1111, Ahmet=555-1234, Mert=555-2222}
HashMap:       {Ahmet=555-1234, Mert=555-2222, Zeynep=555-1111}
TreeMap:       {Ahmet=555-1234, Mert=555-2222, Zeynep=555-1111}

The expressions new HashMap<>(contacts) and new TreeMap<>(contacts) are constructors that copy all the pairs of the given map. LinkedHashMap preserves insertion order: Zeynep, Ahmet, Mert. TreeMap arranges the keys in alphabetical order. The order of HashMap is the bucket order, and the alphabetical appearance here is a coincidence. The copying constructor chooses the number of buckets according to the size of the source map: 4 buckets for three pairs. With four buckets, the bucket number is the last 2 bits of the hash value. From the hash values of the measurement program in the section on sets, Ahmet falls in bucket 1, Mert in 2, and Zeynep in 3. If the same three names were put into a table with 16 buckets, their buckets would be 1, 14, and 7, and the order would turn into Ahmet, Zeynep, Mert. That the table has 4 buckets was verified with a measurement program that reads the internal array through reflection. The conclusion is clear: the order of a HashMap depends on the number of buckets, and programs never rely on this order.

Hashtable

Hashtable is an old (Java 1.0), synchronized map class that stores key-value pairs. Its difference from HashMap is that each of its methods is locked. Because of the locking, it is slower than HashMap in single-threaded programs. In multi-threaded programs, ConcurrentHashMap from the java.util.concurrent package is a better choice; it uses finer-grained locking instead of locking the whole table. Today Hashtable is mostly seen in old code.

The second difference of Hashtable is that it does not accept null: neither keys nor values can be null.

Hashtable<String, String> phoneBook = new Hashtable<>();
phoneBook.put("Ahmet", "555-1234");
System.out.println(phoneBook.get("Ahmet"));
System.out.println(phoneBook.containsKey("Ayse"));
// phoneBook.put(null, "x");  → NullPointerException
555-1234
false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()" because "key" is null

In this note's program, the commented line from the slides has been uncommented. The first two outputs are normal; there is no key "Ayse". put(null, "x"), however, throws a NullPointerException. The message tells the cause of the error: to find the bucket, the table wants to call the key's hashCode() method, but the key is null. A null value is also rejected; phoneBook.put("Ayse", null) throws the same exception, this time without a message.

5.5.6SortedMap and TreeMap

SortedMap is the map interface that stores its keys in sorted order; each key appears once. It offers range operations such as the submap and the upper map. TreeMap is derived from AbstractMap and implements the NavigableMap interface. The keys are arranged by the natural order or by a given Comparator. Internally there is a red-black tree as in TreeSet; get, put, and remove are O(log n). Table 5.22 gives the sorted-map methods. Their names and boundary rules are the same as those of the TreeSet methods.

Table 5.22: The sorted-map methods of TreeMap.
MethodPurpose
firstKey() / lastKey()the smallest / the largest key
headMap(to)keys smaller than to (excluded)
tailMap(from)from and the larger keys (included)
subMap(from, to)from included, to excluded
comparator()the Comparator that orders the map (null for the natural order)
put, get, removesame as Map
TreeMap<String, Double> prices = new TreeMap<>();
prices.put("Tablet", 2000.0);
prices.put("Pen", 15.0);
prices.put("Notebook", 40.0);
prices.put("Ruler", 5.0);
System.out.println(prices);
System.out.println(prices.firstKey());
System.out.println(prices.lastKey());
System.out.println(prices.headMap("Pen"));
System.out.println(prices.tailMap("Pen"));
System.out.println(prices.subMap("Notebook", "Ruler"));
{Notebook=40.0, Pen=15.0, Ruler=5.0, Tablet=2000.0}
Notebook
Tablet
{Notebook=40.0}
{Pen=15.0, Ruler=5.0, Tablet=2000.0}
{Notebook=40.0, Pen=15.0}

Whatever order the products are added in, the map is printed in the alphabetical order of the keys: Notebook, Pen, Ruler, Tablet. The smallest key is Notebook and the largest is Tablet. headMap("Pen") gives the keys smaller than Pen and does not include Pen: only Notebook. tailMap("Pen") includes Pen and the keys larger than it. subMap("Notebook", "Ruler") includes Notebook and does not include Ruler. Thanks to the sorted keys, range queries start in O(log n) time; in a HashMap, the same query would require scanning all the keys.

5.5.7Comparing the map classes

Table 5.23: A comparison of the four map classes.
HashMapLinkedHashMapTreeMapHashtable
Traversal orderno guaranteeinsertion ordersorted by keyno guarantee
get / putO(1) averageO(1) averageO(log n)O(1) average, locked
null keyoneonenono
null valueyesyesyesno
Synchronizednononoyes (legacy)
When?the default choiceorder must be preservedsorted keys, range querieslegacy code

The logic in the table also holds for sets. HashSet, LinkedHashSet, and TreeSet internally use HashMap, LinkedHashMap, and TreeMap, respectively; the elements of the set are the keys of the map. So the order, speed, and null rule of a set are the same as those of the corresponding map.

5.6The Iterator

A list works with indices, a set with a hash table, a TreeSet with a tree, and an ArrayDeque with a circular array. Traversing the elements of such different structures with a single form of loop is possible only through a common intermediary. This intermediary is the iterator. Each collection produces an iterator that knows its own internal structure; the user only asks "is there a next element?" and "give me the next one".

5.6.1The Iterator interface

Definition 5.14

An iterator is an object that gives the elements of a collection one by one. It makes it possible to reach every element without knowing the internal structure of the collection. The safe way to remove while traversing is the iterator's remove() (for bulk removal, removeIf). The iterator() method of every Iterable collection returns an iterator.

Table 5.24: The methods of the Iterator<E> interface.
MethodPurpose
hasNext()is there a next element?
next()returns the next element and advances the cursor
remove()removes from the collection the element obtained by the last next()

The easiest way to understand an iterator is to imagine a cursor. The cursor sits not on the elements but between them. At the start it is in front of the first element. next() makes the cursor hop over one element and returns the element it hopped over. hasNext() tells whether any elements remain in front of the cursor. Figure 5.21 shows this arrangement.

385cursornext() → 3hasNext() → true
Figure 5.21: The iterator's cursor sits between the elements. next() has returned 3 and moved the cursor between 3 and 8; hasNext() is true.
ArrayList<Integer> list = new ArrayList<>();
list.add(3);
list.add(8);
list.add(5);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
    Integer num = iterator.next();
    // process the element here
    System.out.println(num);
}
3
8
5

An iterator is usually used with a while (it.hasNext()) loop. Table 5.25 traces the loop step by step.

Table 5.25: Tracing a traversal with an iterator. The cursor position is given by the index of the element in front of the cursor; index 3 means the end of the list.
StepLineList and cursorVariablesNew output
11: ArrayList<Integer> list = new ArrayList<>();
2: list.add(3);
3: list.add(8);
4: list.add(5);
list 3, 8, 5——
25: Iterator<Integer> iterator = list.iterator();list 3, 8, 5; cursor before element 0——
36: while (iterator.hasNext()) {
7: Integer num = iterator.next();
list 3, 8, 5; cursor before element 1num=3—
49: System.out.println(num);list 3, 8, 5; cursor before element 1num=33
56: while (iterator.hasNext()) {
7: Integer num = iterator.next();
list 3, 8, 5; cursor before element 2num=8—
69: System.out.println(num);list 3, 8, 5; cursor before element 2num=88
76: while (iterator.hasNext()) {
7: Integer num = iterator.next();
list 3, 8, 5; cursor at the endnum=5—
89: System.out.println(num);list 3, 8, 5; cursor at the endnum=55
96: while (iterator.hasNext()) {list 3, 8, 5; cursor at the endnum=5—

list.iterator() puts the cursor in front of the first element. In each round of the loop, hasNext() returns true, next() gives the next element and advances the cursor. After three rounds the cursor is at the end. hasNext() returns false and the loop ends. If next() is called when no elements remain, a NoSuchElementException is thrown.

The for-each loop is translated behind the scenes into exactly this iterator loop. When you write for (Integer num : list) { … }, the compiler creates an iterator and inserts the hasNext/next calls itself. The Java Language Specification defines this translation precisely. This is also why for-each works only on Iterable types.

5.6.2Removing while traversing

Removing from a list the elements that satisfy a certain condition is a common job. The most natural-looking way is to call the list's own remove method inside a for-each. This way is wrong:

List<Integer> numbers = new ArrayList<>(Arrays.asList(4, 7, 10, 13, 16));
for (Integer s : numbers) {
    if (s % 2 == 0) {
        numbers.remove(s);
    }
}
Exception in thread "main" java.util.ConcurrentModificationException

The first even number, 4, is removed, but right after that the program stops with a ConcurrentModificationException. The correct way is to write the iterator explicitly and call its own remove() method:

List<Integer> numbers = new ArrayList<>();
Collections.addAll(numbers, 4, 7, 10, 13, 16);
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
    if (it.next() % 2 == 0) {
        it.remove();         // safe removal
    }
}
System.out.println(numbers);

it.next() takes the element, and it is checked whether it is even. If it is, it.remove() removes the element last taken from the list. Since the iterator does the removal itself, it also updates its internal state and the traversal continues undisturbed. Java 8 brought a short way to do the same job: removeIf. The condition is given as a lambda expression and the method builds the loop itself:

List<Integer> s2 = new ArrayList<>();
Collections.addAll(s2, 4, 7, 10, 13, 16);
s2.removeIf(s -> s % 2 == 0);
System.out.println(s2);
[7, 13]
[7, 13]

The output of both ways is the same: only the odd numbers remain. ArrayList.removeIf first marks the elements to be removed, then shifts the remaining ones left in a single pass. So the total work is O(n). Removing one by one with an iterator, on the other hand, shifts the elements behind on each removal and in the worst case grows to O(n²). On large lists removeIf is both shorter and faster.

it.remove() can be called at most once after each next(); otherwise an IllegalStateException is thrown.

Common mistake

Removing while moving forward in an indexed loop. The loop for (int i = 0; i < a.size(); i++) if (a.get(i) % 2 == 0) a.remove(i); does not throw an exception, but can give a wrong result. When an element is removed, the element behind it shifts into its index and i++ skips that element. In the list [4, 10, 7, 13, 16], 4 is removed, 10 shifts to index 0 and is never checked. In this note's program the result was [10, 7, 13]. If the same loop is built from the end toward the start, the shifting does not affect unchecked elements and the result comes out right: [7, 13].

5.6.3Where does ConcurrentModificationException come from?

To understand why removal inside a for-each throws an exception, we need to look inside the iterator. ArrayList has a field modCount. This field is the list's structural-modification counter: every insertion and removal increases it by one. At the moment the iterator is created, it stores the value of this counter as expectedModCount and also keeps a cursor. Each next() call first compares the two counters. If they differ, the list has been modified without the iterator's knowledge and it is not safe to continue the traversal. In this case the iterator throws a ConcurrentModificationException. This behavior is called fail-fast. The fail-fast check is best effort, not a guarantee: some modifications can pass without an exception, so the correctness of a program is never based on this exception.

List<Integer> s = new ArrayList<>();
Collections.addAll(s, 6, 9, 12);
for (Integer x : s) {      // hidden Iterator
    if (x % 2 == 0) {
        s.remove(x);
    }
}
System.out.println(s);

Table 5.26 traces the program together with the counters.

Table 5.26: Tracing removal inside a for-each.
StepLineVariablesNew output
11: List<Integer> s = new ArrayList<>();
2: Collections.addAll(s, 6, 9, 12);
s=[6, 9, 12], modCount=0—
23: for (Integer x : s) { // hidden Iterators=[6, 9, 12], modCount=0—
33: for (Integer x : s) { // hidden Iterators=[6, 9, 12], modCount=0, hasNext=true—
43: for (Integer x : s) { // hidden Iterators=[6, 9, 12], modCount=0, x=6—
54: if (x % 2 == 0) {s=[6, 9, 12], modCount=0, x=6—
65: s.remove(x);s=[9, 12], modCount=1, x=6—
73: for (Integer x : s) { // hidden Iterators=[9, 12], modCount=1, hasNext=true—
83: for (Integer x : s) { // hidden Iterators=[9, 12], modCount=1Exception in thread "main" java.util.ConcurrentModificationException

The list has three elements and modCount is 0. The for-each secretly calls s.iterator(): cursor = 0, expectedModCount = 0. The first hasNext() returns true because cursor (0) and size (3) differ. next() first compares the counters (0 = 0), returns 6, and sets cursor to 1. 6 is even and s.remove(x) is called. This is the list's own method: 9 and 12 shift left, size drops to 2, and modCount rises to 1. The iterator knows nothing about this. Figure 5.22 shows this moment and what follows.

s (internal array)901212size = 2cursor = 1modCount = 1expected = 0≠ s (internal array)901212size = 2cursor = 1modCount = 1expected = 0≠ConcurrentModificationException
Figure 5.22: On the left, after s.remove(6): the list is [9, 12], modCount = 1, the iterator's expected value is still 0, and cursor = 1. On the right, the following next(): the counters do not match and a ConcurrentModificationException is thrown.

The next hasNext() returns true because cursor (1) and size (2) differ; the loop continues. But when next() compares the counters, modCount is 1 and expectedModCount is 0. The exception is thrown and println is never reached.

Exception in thread "main" java.util.ConcurrentModificationException

The trace shows one more thing: the exception appears not at the moment of removal but at the next next(). If hasNext() returns false after the removal, next() is never called and no exception occurs. Had the list been {6, 9}, after 6 is removed cursor would be 1 and size 1. hasNext() would return false and the loop would end silently:

[9]

The program ends without error, but 9 was never checked. Wrong code sometimes seems to work. That is why saying "it worked for me" is not enough. Removal while traversing is always done with the iterator's remove or with removeIf. The word "concurrent" in the name of the exception can be misleading. This error is not specific to multi-threaded programs; it occurs in a single-threaded program too, as it does here.

5.7Algorithms

The third element of the Collections Framework is the ready-made algorithms. Most of them are gathered in the java.util.Collections class. This section covers, in turn, the algorithms for sorting, defining an order (Comparable and Comparator), shuffling, searching, and composition.

5.7.1The Collections class

Two names are often confused. Collection is an interface and defines the methods common to all collections. Collections (with an "s" at the end) is a utility class that gathers ready-made static methods that operate on collections. No objects are created from this class; its methods are called with the class name, as in Collections.sort(list).

These algorithms are fast and tested; writing the same job by hand both takes time and carries the risk of errors. They fall into four groups:

  • Sorting: sort, reverse, reverseOrder.
  • Shuffling: shuffle.
  • Searching: binarySearch, max, min, frequency.
  • Composition: copy, fill, swap, reverse.

5.7.2Sorting

List<String> names = new ArrayList<>(
        Arrays.asList("Cem", "Ayse", "Banu", "Ali"));
Collections.sort(names);
System.out.println(names);
Collections.sort(names, Collections.reverseOrder());
System.out.println(names);
Collections.reverse(names);
System.out.println(names);
[Ali, Ayse, Banu, Cem]
[Cem, Banu, Ayse, Ali]
[Ali, Ayse, Banu, Cem]

Collections.sort(names) sorts the list by its natural order, that is, alphabetically. The second call takes a comparator: Collections.reverseOrder() reverses the natural order and the list is arranged from Z to A. Collections.reverse, on the other hand, makes no comparisons at all; it reverses the current order of the list. When a list in descending order is reversed, ascending order is obtained again. Table 5.27 summarizes the three methods.

Table 5.27: Sorting methods.
MethodPurpose
sort(list)by the natural order; the elements must be Comparable
sort(list, c)by the given comparator (Comparator)
reverse(list)reverses the list

Classes such as String, Integer, and Double are already Comparable. Since Java 8 the list also has its own sort method: list.sort(null) sorts by the natural order and list.sort(c) by a comparator. If a list whose elements cannot be compared is given to Collections.sort, the error is caught at compile time:

StudentSort.java:9: error: no suitable method found for sort(List<Student>)
        Collections.sort(l);
                   ^
    method Collections.<T#1>sort(List<T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: Student
        upper bounds: Comparable<? super T#1>)
    method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
    T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
1 error

The message is long, but its essence is on a single line: the type Student does not satisfy the upper bound Comparable<? super T>; that is, it is not comparable. The second form suggested, sort(List, Comparator), does not fit either because the number of arguments does not match. Unlike the run-time error in the priority queue, here the compiler sees the problem in advance; the signature of sort restricts the type parameter.

Collections.sort uses the TimSort algorithm on object lists. TimSort is an adapted variant of merge sort. It takes O(n log n) in the worst case and is much faster on partially sorted data. It is also stable: the relative order of elements considered equal is preserved. Arrays.sort(int[]), which sorts primitive arrays, uses Dual-Pivot Quicksort; this choice was made because stability is meaningless for primitive values. This note's program sorted the list "Cem:B, Ali:A, Ece:B, Banu:A, Can:A" by letter grade only. The result is [Ali:A, Banu:A, Can:A, Cem:B, Ece:B]: those with the same grade keep their old order in the list. In this way, when an alphabetical list is sorted by grade, those with the same grade stay alphabetical.

5.7.3Comparable: natural ordering

Definition 5.15

Natural ordering is the default order that a class defines by implementing the Comparable<T> interface and writing the compareTo method. If a.compareTo(b) is negative, a comes first; if 0, the two are equal; if positive, b comes first.

class Student implements Comparable<Student> {
    String name;
    int score;

    Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    // ascending by score
    @Override
    public int compareTo(Student other) {
        return Integer.compare(score, other.score);
    }

    @Override
    public String toString() {
        return name + ":" + score;
    }
}
List<Student> roster = new ArrayList<>();
roster.add(new Student("Cem", 72));
roster.add(new Student("Ayse", 95));
roster.add(new Student("Banu", 60));

Collections.sort(roster);
System.out.println(roster);
[Banu:60, Cem:72, Ayse:95]
[Ayse:95, Banu:60, Cem:72]
[Banu:60, Cem:72, Ayse:95]
[Ayse:95, Cem:72, Banu:60]

The Student class implements Comparable<Student> and defines ascending order by score. Collections.sort(roster) uses this order: Banu (60), Cem (72), Ayse (95). The following lines of the program are comparator examples and are explained in the next subsection.

In the body of compareTo, Integer.compare(score, other.score) is used. It looks as though the same job could be done with return score - other.score;: if the difference is negative, this is smaller. As long as the scores are small numbers, this works correctly. But the difference of two very large numbers of opposite sign exceeds the int range and the sign flips:

public class Overflow {
    public static void main(String[] args) {
        int a = 2_000_000_000, b = -2_000_000_000;
        System.out.println((a - b) + " " + Integer.compare(a, b));
    }
}
-294967296 1

2 billion is greater than −2 billion, and the difference should be positive. But 4 billion does not fit in an int, and the result comes out negative; the sorting would be wrong. Integer.compare does not subtract; it only compares, and gives the correct result (1). So instead of subtraction, always use Integer.compare (or Double.compare).

There are a few rules a good compareTo must obey. If a comes before b, then b must come after a. If a comes before b and b before c, then a must come before c. It is also recommended that objects for which compareTo returns 0 have equals return true. This last rule matters for TreeSet and TreeMap: these structures test equality not with equals but with compareTo. If two different students with the same score are put into a TreeSet, the second is considered a "duplicate" and is not added.

5.7.4Comparator: another order

Definition 5.16

A comparator is a separate ordering criterion written outside the class. It implements the Comparator<T> interface and compares two objects with the compare(a, b) method. A class has a single natural order but can have as many comparators as desired.

Collections.sort(roster, new Comparator<Student>() {
    @Override
    public int compare(Student a, Student b) {
        return a.name.compareTo(b.name);   // by name
    }
});
System.out.println(roster);

// Java 8+: the same, shorter
roster.sort(Comparator.comparing(o -> o.score));
System.out.println(roster);

This code is the continuation of the previous program and produces the second and third lines of the output. In the classic form, the comparator is written as an anonymous class: new Comparator<Student>() { … } is a class that has no name, is defined in place, and has only one object created. This comparator compares the names with the compareTo of String, and the list becomes alphabetical: Ayse, Banu, Cem.

With Java 8 the same job shrinks to one line. Comparator.comparing(o -> o.score) takes a function that extracts the score from each student and produces a comparator that compares by these values. The list returns to score order. For reverse order, .reversed() is added. The last line in this note's program does this: with Comparator.comparing((Student o) -> o.score).reversed(), the list starts with the highest score. In this form the parameter type of the lambda must be given explicitly; the .reversed() chain prevents the compiler from inferring the type from the left.

5.7.5Shuffling

Shuffling puts the elements of a collection into a random order. Dealing cards, drawing lots, and randomizing the order of questions in an exam are typical uses. Collections.shuffle(list) uses the Fisher–Yates (Knuth) algorithm. The algorithm starts from the end of the list. At each step, it picks one at random from among the elements not yet placed and swaps it with the element at the current position. In a list of n elements, n − 1 swaps are made and the work is O(n). The valuable property of the algorithm is that every possible ordering occurs with equal probability (uniform distribution).

List<String> students = new ArrayList<>(
        Arrays.asList("Ali", "Banu", "Cem", "Deniz"));
Collections.shuffle(students);
System.out.println(students);

The output of this program differs on every run; the [Cem, Ali, Deniz, Banu] in the slides is only one of the 24 possible orderings. When writing tests, or when a result must be reproduced, the same shuffle is wanted. For this, a random number generator with a fixed seed is given as the second argument: Collections.shuffle(students, new Random(42)). This note's program shuffles the same list twice with seed 42, and the two results are exactly the same:

[Deniz, Banu, Ali, Cem]
[Deniz, Banu, Ali, Cem]

The lottery example

A nice application of shuffling is random selection without repetition. The numbers from 1 to 49 are put in a list, the list is shuffled, and the first 6 elements are taken:

public class Lottery {
    // draws lottery numbers
    public static Integer[] draw(int total, int count) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for (int i = 0; i < total; i++) {
            numbers.add(i + 1);          // 1 … total
        }
        Collections.shuffle(numbers);    // shuffle
        Integer[] drawn = new Integer[count];
        for (int i = 0; i < count; i++) {
            drawn[i] = numbers.get(i);
        }
        return drawn;
    }

    public static void main(String[] args) {
        Integer[] result = draw(49, 6);   // 6 out of 49
        for (Integer item : result) {
            System.out.print(item + " ");
        }
    }
}

The output of one run is as follows (it differs on every run):

21 25 16 3 33 46

Because shuffling only moves the numbers around, every number occurs exactly once in the list. So the first six elements are free of repeats, too. This note's test program called draw(49, 6) 10,000 times and checked that every result contained 6 distinct numbers in the range 1–49; the number of errors is 0. The cost is the cost of building and shuffling the whole list, independent of the count of numbers selected: total numbers, that is, O(n).

5.7.6Searching

There are two basic ways to search for an element in a collection.

Linear search
Checks the elements one by one from start to finish. The collection need not be sorted. It is effective on small collections. Its cost is O(n). indexOf and contains perform linear search.
Binary search
In a sorted collection, it looks at the middle element. If the sought value is smaller, it continues the search in the left half; if larger, in the right half. At each step the range is halved. Its cost is O(log n). The collection must be sorted.
List<Integer> numbers = Arrays.asList(1, 3, 5, 7, 9, 11);
System.out.println(Collections.binarySearch(numbers, 7));
System.out.println(Collections.binarySearch(numbers, 6));
System.out.println(numbers.indexOf(7));    // linear search
3
-4
3
-1 -7
2

The first three lines are the output in the slides. binarySearch(numbers, 7) finds 7 at index 3. The search proceeds in these steps. The range is 0–5; the middle index 2 holds 5, which is smaller than 7, and the search moves to the right half. The range is 3–5; the middle index 4 holds 9, which is greater than 7, and it moves to the left half. The range is 3–3 and the 7 at index 3 is found. Three comparisons were made. This note's counting program verifies this number by adding a counter to the comparator:

7: result 3, 3 comparisons
6: result -4, 3 comparisons
1 million elements, max over tried values: 20

6 is not in the list. When the search ends, the place where 6 should go, that is, the insertion point, is 3: after 5 and before 7. For a value that is not found, the return is −(insertion point) − 1: −(3) − 1 = −4. This form carries two pieces of information at once. If the result is negative, the element is absent; −(result) − 1 gives the place where the element would be inserted without breaking the order. The answer to "why not just −3?" is 0: if the insertion point were 0, −0 = 0 would result and be confused with "found at index 0". The fourth line of this note's program shows the edge cases. When 0 is searched for, the insertion point is 0 and the return is −1. When 12 is searched for, the insertion point is 6 (the end of the list) and the return is −7.

If the list is not sorted, the result is undefined. The last line of the program searches for 7 in an unsorted list and returns 2. 7 is indeed at index 2, but this correct result is a coincidence. Had another value been searched for, a wrong index or "absent" could have come back. binarySearch does not check whether the list is sorted; this check is not made because it would take O(n).

The difference between the two searches is striking on large data. In a million elements, linear search makes up to a million comparisons. Binary search makes at most 20 comparisons, because 2²⁰ ≈ 1 million. The last line of the counting program shows that among the values tried in a list of a million elements, at most 20 comparisons were made. A list that is searched often is sorted once and then used with binary search. Sorting takes O(n log n), but every later search is O(log n).

5.7.7Composition algorithms

Composition algorithms copy the elements of a list, change them, swap their places, or count them. Table 5.28 collects them.

Table 5.28: Composition algorithms.
MethodPurpose
copy(dest, src)copies the elements of the source to the beginning of the destination; dest.size() ≥ src.size() is required
fill(list, d)sets all elements to d
reverse(list)reverses the order of the elements
swap(list, i, j)swaps positions i and j
max / minthe largest / the smallest element
frequency(c, o)how many times o occurs
List<Integer> n = Arrays.asList(4, 9, 2, 9, 5);
System.out.println(Collections.max(n));
System.out.println(Collections.min(n));
System.out.println(Collections.frequency(n, 9));
9
2
2

max and min look at all the elements of the list and give the largest and the smallest by natural order: 9 and 2. frequency(n, 9) counts how many times 9 occurs: 2. All three traverse the list once and are O(n). The list need not be sorted.

List<String> names =
        Arrays.asList("Ahmet", "Ayse", "Cem");
List<String> target = new ArrayList<>(
        Arrays.asList("X", "Y", "Z", "W"));
Collections.copy(target, names);
System.out.println(target);
Collections.reverse(target);
System.out.println(target);
Collections.swap(target, 0, 2);
System.out.println(target);
Collections.fill(target, "Java");
System.out.println(target);
[Ahmet, Ayse, Cem, W]
[W, Cem, Ayse, Ahmet]
[Ayse, Cem, W, Ahmet]
[Java, Java, Java, Java]

Table 5.29 gives the four operations step by step.

Table 5.29: Tracing the composition operations.
StepLineListsNew output
11: List<String> names =
2: Arrays.asList("Ahmet", "Ayse", "Cem");
3: List<String> target = new ArrayList<>(
4: Arrays.asList("X", "Y", "Z", "W"));
Ahmet, Ayse, Cem; target: X, Y, Z, W—
25: Collections.copy(target, names);
6: System.out.println(target);
Ahmet, Ayse, Cem; target: Ahmet, Ayse, Cem, W[Ahmet, Ayse, Cem, W]
37: Collections.reverse(target);
8: System.out.println(target);
Ahmet, Ayse, Cem; target: W, Cem, Ayse, Ahmet[W, Cem, Ayse, Ahmet]
49: Collections.swap(target, 0, 2);
10: System.out.println(target);
Ahmet, Ayse, Cem; target: Ayse, Cem, W, Ahmet[Ayse, Cem, W, Ahmet]
511: Collections.fill(target, "Java");
12: System.out.println(target);
Ahmet, Ayse, Cem; target: Java, Java, Java, Java[Java, Java, Java, Java]

names is a fixed-size list created with Arrays.asList. target is a modifiable ArrayList with four elements. copy writes the three elements of the source to positions 0, 1, and 2 of the target. The fourth element of the target, W, stays in place; copy does not change the length of the target. reverse reverses the order: [W, Cem, Ayse, Ahmet]. swap(target, 0, 2) exchanges positions 0 and 2: W and Ayse change places. fill sets all elements to "Java"; the size is still 4. Figure 5.23 shows two intermediate states.

namesAhmetAyseCemtargetAhmet0Ayse1Cem2W3 namesAhmetAyseCemtargetAyse0Cem1W2Ahmet3
Figure 5.23: On the left, after copy: target is [Ahmet, Ayse, Cem, W]. On the right, after reverse and swap(target, 0, 2): [Ayse, Cem, W, Ahmet].

The destination requirement of copy often causes mistakes. If the destination is shorter than the source, an exception is thrown. The real trap is a list that has enough capacity but is empty. new ArrayList<>(10) allocates 10 cells, but its size is 0; copy looks at the size, not the capacity:

import java.util.*;
public class EmptyTarget {
    public static void main(String[] args) {
        List<String> source = Arrays.asList("a", "b", "c");
        List<String> target = new ArrayList<>(10);
        System.out.println(target.size());
        Collections.copy(target, source);
    }
}
0
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest

If an independent copy of a list is needed, the copying constructor is used instead of copy: new ArrayList<>(source). This way does not care about the size of the target and is a single line.

5.8The Stream API

Most of the jobs in the earlier sections follow the same pattern: traverse a collection, select some elements, transform them, and collect the result in a new collection. This pattern requires writing a loop, a condition, and an intermediate list every time. The Stream API, introduced in Java 8, makes it possible to write the same job as a pipeline.

5.8.1Streams and pipelines

Definition 5.17

A stream is an object in the java.util.stream package that processes a sequence of data as a pipeline. The pipeline consists of a source, zero or more intermediate operations, and a terminal operation. The programmer says "what to do"; the library builds the loop.

The stream here is a different concept from input/output (I/O) streams such as InputStream; only the names are the same. A stream does not store data. It passes over a source (a list, an array, the lines of a file) and does not modify the source. Figure 5.24 shows a pipeline.

sourcegrades.stream()intermediate operationsfilter(n ≥ 50)intermediate operationsmap(n + 5)intermediate operationssorted()terminal operationcollect(...)45 82 67 90 38 7582 67 90 7587 72 95 8072 80 87 95[72, 80, 87, 95]intermediate operations return a new stream; computation happens only when the terminal operation is called
Figure 5.24: A stream pipeline. The source is grades.stream(); the intermediate operations are filter(n ≥ 50), map(n + 5), and sorted(); the terminal operation is collect(...). Under each box are the values that pass through that stage. Intermediate operations return a new stream; the pipeline runs only when the terminal operation is called.
List<Integer> grades = Arrays.asList(45, 82, 67, 90, 38, 75);
List<Integer> passed = grades.stream()
    .filter(n -> n >= 50)
    .map(n -> n + 5)
    .sorted()
    .collect(Collectors.toList());
System.out.println(passed);
[72, 80, 87, 95]
[45, 82, 67, 90, 38, 75]
[72, 80, 87, 95]
[72, 80, 87, 95]

The pipeline has four steps. filter lets through the grades of 50 and above: 82, 67, 90, 75. map adds 5 to each: 87, 72, 95, 80. sorted sorts them. collect(Collectors.toList()) gathers the result in a new list. In the note's program, the second line shows that the source did not change, the third line shows the short form in Java 16 (.toList()), and the fourth line shows the same job written with a loop. The loop version needs an intermediate list, a condition, and a separate sort call. The stream version names each step. The required imports are java.util.* and java.util.stream.Collectors.

There is a small difference between Collectors.toList() and .toList(). The first returns a modifiable list (in practice an ArrayList). The second returns an unmodifiable list; if add is called on it, an UnsupportedOperationException is thrown.

5.8.2Intermediate and terminal operations

Table 5.30: Intermediate and terminal operations.
Intermediate operationPurposeTerminal operationResult
filter(p)lets through those that satisfy the conditioncollect(...)list, set, map…
map(f)transforms each elementforEach(f)an action for each element
flatMap(f)flattens nested streamscount()number of elements (long)
sorted()sorts (waits for all elements)reduce(...)reduces the elements to a single value
distinct()discards duplicates (equals)findFirst()the first element (Optional)
limit(n) / skip(n)takes / skips the first n elementsanyMatch / allMatch / noneMatchboolean
peek(f)observes the elements (debugging)min / maxOptional

An intermediate operation returns a new stream and the chain continues. A terminal operation returns a result outside the stream (or nothing) and runs the pipeline. A pipeline without a terminal operation does nothing. A few of the operations in the table were tried in this note's program:

import java.util.*;
import java.util.stream.*;
public class Main68 {
    public static void main(String[] args) {
        List<List<Integer>> nested = Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), Arrays.asList(4, 5));
        System.out.println(nested.stream().flatMap(List::stream).collect(Collectors.toList()));
        System.out.println(Stream.of(3, 1, 3, 2, 1).distinct().collect(Collectors.toList()));
        System.out.println(Stream.of(1, 2, 3, 4, 5, 6).skip(2).limit(3).collect(Collectors.toList()));
        System.out.println(Stream.of(4, 8, 15).count());
        System.out.println(Stream.of(4, 8, 15).anyMatch(x -> x > 10) + " " + Stream.of(4, 8, 15).allMatch(x -> x > 3)
                + " " + Stream.of(4, 8, 15).noneMatch(x -> x > 20));
        System.out.println(Stream.of(4, 8, 15).max(Integer::compare) + " " + Stream.<Integer>empty().findFirst());
        Stream.of("a", "b").peek(s -> System.out.print("peek " + s + "; ")).forEach(s -> System.out.print("forEach " + s + "; "));
        System.out.println();
        long n = Stream.of(1, 2, 3).peek(x -> System.out.print("unseen ")).count();
        System.out.println("count " + n);
    }
}
[1, 2, 3, 4, 5]
[3, 1, 2]
[3, 4, 5]
3
true true true
Optional[15] Optional.empty
peek a; forEach a; peek b; forEach b;
count 3

flatMap unrolls the three inner lists into a single stream of numbers. distinct discards the repeated 3 and 1 and preserves the order of first appearance. skip(2).limit(3) skips the first two elements and takes the next three. max gives its result inside an Optional; on an empty stream findFirst returns Optional.empty. The peek line shows that the elements pass through the pipeline one at a time: "peek a" is immediately followed by "forEach a". The last line is a warning. Because JDK 21 knows the result of count() directly from the size of the source, it does not run the pipeline at all and the text in peek is never seen. peek is for debugging only; the real work is not put inside it.

5.8.3Lazy evaluation and single use

Definition 5.18

Lazy evaluation: when intermediate operations are called, they process no elements; they merely record a recipe. The elements are processed when the terminal operation is called, passing through the pipeline one at a time.

List<String> names =
    Arrays.asList("Arda", "Ece", "Ayse", "Can");
Stream<String> pipe = names.stream()
    .filter(s -> s.startsWith("A"))
    .map(String::toUpperCase);
// nothing processed yet.
List<String> result =
    pipe.collect(Collectors.toList());
System.out.println(result);  // [ARDA, AYSE]
pipe.count();   // IllegalStateException
[ARDA, AYSE]
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

The pipe variable is a Stream<String>. When the first three lines have run, no name has yet been filtered and no letter capitalized. When collect is called, the pipeline runs and the result is [ARDA, AYSE]. String::toUpperCase is a method reference; it is the short form of the lambda s -> s.toUpperCase(). The last line shows the second rule: a stream is single-use. If the same stream is used again after a terminal operation, an IllegalStateException is thrown. If necessary, a new stream is taken from the source: names.stream().

Laziness has two important consequences. First, the elements pass through the pipeline one at a time. The first element goes through filter and map, and only then does the second element arrive. Second, operations such as findFirst and limit stop when they find the result and the remaining elements are never processed. This makes it possible to work even with an infinite source: Stream.iterate(1, x -> x * 2).filter(x -> x > 100).findFirst() finds 128 in a stream that goes on forever as 1, 2, 4, … and stops. sorted is the exception to this rule: to be able to sort, it must first collect all the elements.

import java.util.*;
import java.util.stream.*;
public class SortedWaits {
    public static void main(String[] args) {
        List<Integer> l = Stream.of(3, 1, 2)
            .peek(x -> System.out.println("before " + x))
            .sorted()
            .peek(x -> System.out.println("after " + x))
            .collect(Collectors.toList());
        System.out.println(l);
    }
}
before 3
before 1
before 2
after 1
after 2
after 3
[1, 2, 3]

The three "before" lines come before the "after" lines; sorted is a waiting point in the pipeline; it passes no element forward until all the elements have arrived.

5.8.4Tracing a stream pipeline step by step

To see laziness with our own eyes, let us add a print line to each of filter and map:

List<String> names = Arrays.asList("Arda", "Ece", "Ayse", "Can");
Stream<String> pipe = names.stream()
    .filter(s -> { System.out.println("filter " + s);
                   return s.startsWith("A"); })
    .map(s -> { System.out.println("map " + s);
                return s.toUpperCase(); });
System.out.println("pipe ready");
List<String> result = pipe.collect(Collectors.toList());
System.out.println(result);
pipe ready
filter Arda
map Arda
filter Ece
filter Ayse
map Ayse
filter Can
[ARDA, AYSE]
Table 5.31: Tracing the lazy stream pipeline.
StepLineVariablesNew output
11: List<String> names = Arrays.asList("Arda", "Ece", "Ayse", "Can");
2: Stream<String> pipe = names.stream()
3: .filter(s -> { System.out.println("filter " + s);
4: return s.startsWith("A"); })
5: .map(s -> { System.out.println("map " + s);
6: return s.toUpperCase(); });
names=[Arda, Ece, Ayse, Can], pipe=Stream—
27: System.out.println("pipe ready");pipe=Streampipe ready
38: List<String> result = pipe.collect(Collectors.toList());
3: .filter(s -> { System.out.println("filter " + s);
4: return s.startsWith("A"); })
s="Arda"filter Arda
48: List<String> result = pipe.collect(Collectors.toList());
5: .map(s -> { System.out.println("map " + s);
6: return s.toUpperCase(); });
s="Arda"map Arda
58: List<String> result = pipe.collect(Collectors.toList());
3: .filter(s -> { System.out.println("filter " + s);
4: return s.startsWith("A"); })
s="Ece"filter Ece
68: List<String> result = pipe.collect(Collectors.toList());
3: .filter(s -> { System.out.println("filter " + s);
4: return s.startsWith("A"); })
s="Ayse"filter Ayse
78: List<String> result = pipe.collect(Collectors.toList());
5: .map(s -> { System.out.println("map " + s);
6: return s.toUpperCase(); });
s="Ayse"map Ayse
88: List<String> result = pipe.collect(Collectors.toList());
3: .filter(s -> { System.out.println("filter " + s);
4: return s.startsWith("A"); })
s="Can"filter Can
98: List<String> result = pipe.collect(Collectors.toList());result=[ARDA, AYSE]—
109: System.out.println(result);result=[ARDA, AYSE][ARDA, AYSE]

While the pipeline is being built, no lambda runs and there is no output. That is why the "pipe ready" line is printed before all the operations. When collect runs the pipeline, the first element, Arda, enters filter, passes because it starts with "A", and goes straight to map. Only then is it the second element's turn. Ece does not satisfy the condition and never reaches map. Ayse passes and is capitalized. Can is eliminated. In the end filter ran 4 times and map only 2 times. Figure 5.25 shows two moments.

sourceArdaEceAyseCanfiltermapArdaresultARDA sourceArdaEceAyseCanfiltermapresultARDAAYSE
Figure 5.25: On the left, Arda has passed filter, reached map, and ARDA has been added to the result; the other elements still wait in the source. On the right, the pipeline has finished: the result holds ARDA and AYSE.

If findFirst is used instead of collect on the same pipeline, the pipeline stops as soon as it finds the first result:

filter Arda
map Arda
ARDA

Only Arda has been processed; no lambda was called for Ece, Ayse, or Can. This is the counterpart of break in code written with a loop.

5.8.5reduce, Collectors, and primitive streams

List<String> fruits = Arrays.asList(
    "pear", "kiwi", "fig", "plum", "lemon");
int total = Arrays.asList(4, 8, 15, 16, 23)
    .stream().reduce(0, Integer::sum);
Map<Integer, List<String>> byLen = fruits
    .stream().collect(
        Collectors.groupingBy(String::length));
String all = fruits.stream()
    .collect(Collectors.joining(", "));
int t = IntStream.rangeClosed(1, 100).sum();
Optional<String> z = fruits.stream()
    .filter(m -> m.startsWith("z")).findFirst();
System.out.println(z.orElse("none"));
none
total = 66
byLen = {3=[fig], 4=[pear, kiwi, plum], 5=[lemon]}
all = pear, kiwi, fig, plum, lemon
t = 5050
OptionalDouble[50.5] OptionalDouble.empty
{3=1, 4=3, 5=1}
20
first p: pear
Optional[27]

reduce(0, Integer::sum) reduces the elements to a single value. The initial value is 0, and each element is added to the previous result: 0 + 4 + 8 + 15 + 16 + 23 = 66. Collectors.groupingBy(String::length) groups the fruits by length and produces a Map<Integer, List<String>>. Collectors.joining(", ") joins the strings with a separator in between. IntStream.rangeClosed(1, 100) is a stream of the int values from 1 to 100. Primitive streams (IntStream, LongStream, DoubleStream) do no boxing and offer ready-made terminal operations such as sum and average; the total is 5050.

The return type of findFirst is Optional<String>. Optional is a container that expresses the "there may be no result" situation explicitly instead of with null. No fruit starts with "z"; orElse("none") returns the given default for an empty container. ifPresent does something only if there is a value. The extra lines show three more things. average returns an OptionalDouble, because the average of an empty stream is undefined. counting() can be given to groupingBy as a second collector. mapToInt moves from an object stream to a primitive stream. Calling get() on an empty Optional throws NoSuchElementException: No value present. That is why orElse or ifPresent is preferred to get.

5.8.6Side effects and parallel streams

Streams describe "what to do"; the lambdas in the pipeline are expected not to change the outside world. A lambda that modifies an outside variable or collection is called side-effecting. The result should be produced with map, collect, and reduce. This rule becomes mandatory in parallel streams. parallel() or parallelStream() splits the work among the threads of the common ForkJoinPool.

List<Integer> list = new ArrayList<>();
IntStream.range(0, 10000).parallel()
    .forEach(list::add);          // WRONG: shared list

List<Integer> safe = IntStream.range(0, 10000).parallel()
    .boxed()
    .collect(Collectors.toList()); // RIGHT: 10000 items

In the first pipeline, several threads call add on the same ArrayList at the same time. ArrayList is not thread-safe. Two threads can write to the same cell, or one can write to the old array while another is growing the internal array. The result varies from run to run. This note's measurement program ran the first pipeline 200 times on a machine with 12 cores:

200 trials: AIOOBE 58, short 91 (min 638, max 10000), exact 51, other 0; cores 12
200 trials: AIOOBE 51, short 145 (min 969, max 10000), exact 4, other 0; cores 12

All three outcomes were seen: ArrayIndexOutOfBoundsException, fewer than 10,000 elements, and sometimes, by chance, the right size. That the correct result appears now and then makes the bug even more dangerous; a test may not catch it. The second pipeline gives 10,000 elements and the correct order on every run. collect gives each thread its own intermediate list and merges them safely at the end.

size 6805
correct 10000 0 9999

A parallel stream is not always fast. Splitting the work, distributing it to threads, and merging the results has a cost. On small data, with cheap operations, with jobs that wait for I/O, and with order-dependent operations (sorted, findFirst), a parallel stream can slow things down. Measure before moving to parallelism. Common mistakes with streams are: using a stream a second time, doing the real work inside peek, filling an outside collection with forEach, and assuming a parallel stream is automatically fast.

5.9Choosing the right collection

5.9.1A selection table

Choosing a collection starts with two questions: which operation will be performed most often, and does order matter? Table 5.32 gives the classes that meet typical needs.

Table 5.32: Choosing a collection by need.
NeedChoiceWhy
Ordered list, access by indexArrayListfast get(i); the default list
Frequent insertion/removal at the front/back, queue, stackArrayDequeO(1) at both ends; faster than Stack and LinkedList
Repeatedly taking the highest-priority elementPriorityQueuepoll gives the smallest (or the highest priority by the criterion)
Unique elements, fast "is it present?"HashSetcontains O(1) on average
Unique + insertion orderLinkedHashSetorder is preserved
Unique + sorted, range queriesTreeSetfirst, headSet, subSet
Fast access from key to valueHashMapget O(1) on average; the default map
Sorted keysTreeMapfirstKey, headMap, subMap

If the variable is declared with an interface type (List, Set, Map, Queue, Deque), only the new line changes when the need changes. First the right interface is chosen, then the implementation.

5.9.2Unmodifiable collections

Some collections are wanted never to change after they are created: the days of the week, a fixed list of colors, a configuration table. The factory methods introduced in Java 9 produce such collections in a single line:

List<String> r = List.of("red", "green");
Set<Integer> primes = Set.of(2, 3, 5);
Map<String, Integer> score =
        Map.of("Ali", 90, "Banu", 85);
System.out.println(r);
System.out.println(score.get("Banu"));
r.add("blue");
[red, green]
85
Exception in thread "main" java.lang.UnsupportedOperationException

List.of, Set.of, and Map.of return immutable collections. Reading is free; add, remove, and put throw UnsupportedOperationException. These collections do not accept null elements. A call with duplicates such as Set.of(1, 1) also throws IllegalArgumentException: duplicate element: 1.

The second way, available since Java 1.2, is Collections.unmodifiableList. This method returns not a new collection but a read-only view:

List<String> list = new ArrayList<>();
list.add("a");
List<String> readOnly =
        Collections.unmodifiableList(list);
list.add("b");
System.out.println(readOnly);
readOnly.add("c");
[a, b]
[a, b, x] [a, b]
Exception in thread "main" java.lang.UnsupportedOperationException

No change can be made through the readOnly view, but if the underlying list changes, the view changes too: when "b" is added, readOnly becomes [a, b]. In this note's program an independent copy was also taken with List.copyOf(list) (Java 10+). Then "x" is added to the list; the view shows it, while the copy remains [a, b]. To hand a list inside a class to the outside as "read only", a view is used; for a truly constant list, List.of or List.copyOf is used. Unmodifiable collections are also safe choices for hash keys and constants.

5.10Solved problems

Example 5.1

What does the following program print? When fibonacci(10) returns, how many elements are in the list and what are the last three? How many times does the loop run in the call fibonacci(1)? Is a list really needed for this job?

public class Fibonacci {
    public static int fibonacci(int num) {
        List<Integer> list = new ArrayList<>();
        list.add(0);
        list.add(1);
        for (int i = 2; i < num + 1; i++) {
            list.add(list.get(i - 2) + list.get(i - 1));
        }
        return list.get(num);
    }
    public static void main(String[] args) {
        int result = fibonacci(10);
        System.out.println(result);
    }
}

The list starts with 0 and 1. The loop runs nine times, from i = 2 to i = 10, adding the sum of the last two elements in each round. When fibonacci(10) returns, the list has 11 elements (indices 0…10): [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]. The last three are 21, 34, 55, and the program prints 55. In fibonacci(1), 2 < 2 is false for i = 2 and the loop never runs; list.get(1) = 1 is returned. A list is not really needed: two variables holding only the last two values are enough, and the memory drops from O(n) to O(1). This note's program also shows a limit with extra calls:

import java.util.*;
public class Fibonacci {
    public static int fibonacci(int num) {
        List<Integer> list = new ArrayList<>();
        list.add(0);
        list.add(1);
        for (int i = 2; i < num + 1; i++) {
            list.add(list.get(i - 2) + list.get(i - 1));
        }
        return list.get(num);
    }
    public static void main(String[] args) {
        int result = fibonacci(10);
        System.out.println(result);
        System.out.println(fibonacci(1) + " " + fibonacci(0) + " " + fibonacci(46));
        System.out.println(fibonacci(47));
    }
}
55
1 0 1836311903
-1323752223

fibonacci(46) = 1,836,311,903 is the last Fibonacci number that fits in an int. The 47th term exceeds the int limit and, because of overflow, a negative number results. The Integers inside a collection are also bound by the limits of the primitive int; for larger values Long or BigInteger is used.

Example 5.2

What does the following dedup method return? What would change if HashSet or TreeSet were used instead of LinkedHashSet?

public class Dedup {
    static List<String> dedup(List<String> input) {
        Set<String> seen = new LinkedHashSet<>(input);
        return new ArrayList<>(seen);
    }

    public static void main(String[] args) {
        List<String> l = Arrays.asList("b", "a", "b", "c", "a");
        System.out.println(dedup(l));
    }
}
[b, a, c]
[a, b, c] [a, b, c]

new LinkedHashSet<>(input) adds the elements of the list to the set in order; duplicates are discarded and the order of first appearance is preserved. The result is [b, a, c]. TreeSet would give alphabetical order: [a, b, c]. HashSet, on the other hand, guarantees no order. On the second line of the program, the result of HashSet also came out as [a, b, c]; because the hash codes of one-letter strings are consecutive numbers, the buckets happened to coincide with alphabetical order. This is a coincidence and cannot be relied on. The cost of the method is O(n): one O(1)-average insertion for each element.

Example 5.3

Parenthesis balance: every opening parenthesis must be closed with the right kind and in the right order. What do isBalanced("(a[b]c)"), isBalanced("(a[b)c]"), and isBalanced("((") return? Why is a stack used?

static boolean isBalanced(String expr) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : expr.toCharArray()) {
        if (c == '(' || c == '[') {
            stack.push(c);
        } else if (c == ')' || c == ']') {
            if (stack.isEmpty()) return false;
            char open = stack.pop();
            if (c == ')' && open != '(') return false;
            if (c == ']' && open != '[') return false;
        }
    }
    return stack.isEmpty();
}

An opening parenthesis is pushed onto the stack. When a closing parenthesis arrives, the opening parenthesis at the top of the stack is popped and its kind is compared. If the stack is empty or the kind does not match, the expression is unbalanced. If the stack is not empty at the end, an unclosed parenthesis remains. In "(a[b]c)", when ] arrives [ is on top, and when ) arrives ( is on top, and at the end the stack is empty: true. In "(a[b)c]", when ) arrives [ is on top: false. In "((", two parentheses remain on the stack at the end: false. This note's program also tries three additional expressions ("())", the empty string, and "[(x)](y)"):

true false false false true true

The reason a stack is used is that the most recently opened parenthesis must be the first to close. This is exactly LIFO behavior. The stack was chosen as an ArrayDeque, not a Stack. The method scans the expression once and does O(1) work per character; the total cost is O(n).

Example 5.4

What is the output of the two code fragments? (push = offerFirst, pop = removeFirst.)

Deque<Integer> d = new ArrayDeque<>();
d.offerLast(1);
d.offerFirst(2);
d.offerLast(3);
d.push(4);
System.out.println(d);
System.out.println(d.pollLast() + d.pop());
System.out.println(d);
Map<String, Integer> m = new TreeMap<>();
m.put("b", 1);
m.put("a", 2);
m.put("b", 3);
Set<Integer> s = new TreeSet<>(m.values());
s.add(2);
System.out.println(m + " " + s + " " + m.size());
[4, 2, 1, 3]
7
[2, 1]
{a=2, b=3} [2, 3] 2

The deque changes as follows: 1 → [1]; 2 at the front → [2, 1]; 3 at the back → [2, 1, 3]; push(4) at the front → [4, 2, 1, 3]. pollLast() returns 3 and pop() returns 4. The two Integers are added with +, because there is no string in the expression: 7. The remaining deque is [2, 1]. In the second fragment, "b" becomes 3 with the second put; the map is {a=2, b=3}. The set built from the values is [2, 3]. s.add(2) is not added because it is a duplicate, and the size of the map is 2.

Example 5.5

How is a mostFrequent method, which returns the most frequent word in a String[] array, written with a HashMap?

static String mostFrequent(String[] words) {
    Map<String, Integer> counter = new HashMap<>();
    for (String k : words) {
        counter.put(k, counter.getOrDefault(k, 0) + 1);
    }
    String best = null;
    int maxCount = 0;
    for (Map.Entry<String, Integer> g : counter.entrySet()) {
        if (g.getValue() > maxCount) {
            maxCount = g.getValue();
            best = g.getKey();
        }
    }
    return best;
}
water
null

The first loop counts the words with getOrDefault. The second loop traverses entrySet and keeps the word with the largest count. For "water, tea, water, coffee, water, tea", water (3) is returned. In an empty array there are no words and the method returns null; the caller must check for this case. If two words occur the same number of times, which one is returned depends on the traversal order of the HashMap, that is, it is undefined. The cost is O(n).

Example 5.6

A Map<String, List<Integer>> holding each student's list of grades is built; how are the averages printed for Ali: 80, 90 and Banu: 70?

Map<String, List<Integer>> grades = new TreeMap<>();
grades.put("Ali", new ArrayList<>());
grades.get("Ali").add(80);
grades.get("Ali").add(90);
grades.put("Banu", new ArrayList<>(Arrays.asList(70)));
for (Map.Entry<String, List<Integer>> g : grades.entrySet()) {
    int total = 0;
    for (int n : g.getValue()) {
        total += n;
    }
    System.out.println(g.getKey() + " avg: " + total / g.getValue().size());
}
Ali avg: 85
Banu avg: 70
{Ali=[80, 90]}

The value of the map is a list. grades.get("Ali") returns that list and .add(80) adds directly to it; there is no need to put into the map again. The average is computed with integer division: 170 / 2 = 85. The last line of this note's program shows the computeIfAbsent pattern from Java 8. If the key is absent this method creates and inserts a new list, and if present it returns the existing one; the two steps "first put, then get" shrink into a single call.

The second exercise in the slides writes the lottery draw without shuffle, using a Random and a TreeSet:

Random r = new Random();
Set<Integer> drawn = new TreeSet<>();
while (drawn.size() < 6) {
    drawn.add(r.nextInt(49) + 1);  // 1 … 49
}
System.out.println(drawn);
[1, 32, 37, 40, 43, 45]

The set prevents repetition by itself. If the same number comes a second time, add does not add it and the loop runs one more round. TreeSet keeps the numbers sorted. The output differs on every run. In this method the number of loop rounds is random, but since the probability of a repeat when choosing 6 of 49 numbers is small, it finishes after a few extra rounds.

5.11Common mistakes

This section collects the most frequent mistakes in working with collections, together with the real compiler and run-time messages.

Common mistake

A generic declaration with a primitive type. List<int> does not compile; the type argument must be a reference type. The correct form is List<Integer>; int values are autoboxed.

PrimitiveType.java:4: error: unexpected type
        List<int> grades = new ArrayList<>();
             ^
  required: reference
  found:    int
1 error
Common mistake

Adding an element of the wrong type. add(42) on a List<String> is rejected at compile time. If the number is to be stored as a string, String.valueOf(42) is added.

WrongType.java:5: error: incompatible types: int cannot be converted to String
        names.add(42);
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
Common mistake

Confusing remove(int) with remove(Object). In a List<Integer>, remove(1) deletes index 1. To delete a value, Integer.valueOf(…) is given.

List<Integer> list = new ArrayList<>();
Collections.addAll(list, 10, 20, 30);
list.remove(1);                   // index 1
System.out.println(list);
list.remove(Integer.valueOf(10)); // value 10
System.out.println(list);
Common mistake

Comparing Integers with ==. == checks whether two references point to the same object. Java caches the Integer objects between −128 and 127, and valueOf always returns the same object in this range. That is why a test with 100 happens to give true and one with 1000 gives false. Value comparison is done with equals.

List<Integer> a = new ArrayList<>();
Collections.addAll(a, 1000, 1000);
System.out.println(a.get(0) == a.get(1));
System.out.println(a.get(0).equals(a.get(1)));
[10, 30]
[30]
false
true
true

The first two lines of the output belong to the remove example and the next two to the comparison with 1000. The last line is the test with 100 added to the note's program: the same comparison gives true in the cache range.

Common mistake

Adding to an Arrays.asList list. Arrays.asList returns a fixed-size list backed by the array. set works, add and remove do not. For a modifiable list, write new ArrayList<>(Arrays.asList(…)).

[9, 2, 3]
Exception in thread "main" java.lang.UnsupportedOperationException
Common mistake

A nonexistent index. The valid indices are 0 … size() − 1. In a three-element list, get(3) throws an exception. remove() on an empty queue also throws NoSuchElementException; poll(), on the other hand, returns null.

List<String> l = new ArrayList<>();
Collections.addAll(l, "a", "b", "c");
System.out.println(l.get(3));
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
Common mistake

Sorting Turkish names with the natural order of String. String is sorted by character codes: letters such as Ç, Ö, Ş, Ü, İ, ı come after "Z". The Turkish alphabet order is given by java.text.Collator.

List<String> names = new ArrayList<>();
Collections.addAll(names,
        "Zeynep", "Çağla", "Can", "Ömer");
Collections.sort(names);
System.out.println(names);
Locale tr = Locale.forLanguageTag("tr-TR");
Collections.sort(names, Collator.getInstance(tr));
System.out.println(names);
[Can, Zeynep, Çağla, Ömer]
[Can, Çağla, Ömer, Zeynep]
[Ilgaz, irmik, ufuk, üzüm, İzmir, ılık] [Ilgaz, ılık, irmik, İzmir, ufuk, üzüm]

The first two lines are the output in the slides. The third line, added to the note's program, shows the extent of the problem. In the natural order, the capital "I" comes before the lowercase letters, while "İ" and "ı" fall at the very end. With the Turkish Collator, the order becomes Ilgaz, ılık, irmik, İzmir, ufuk, üzüm. This collator treats the case difference as secondary; "ı" and "i" are separate letters.

5.12Summary

  • The Collections Framework consists of three elements: interfaces (what is done), implementations (how it is done), and the algorithms in the Collections class. Beside the hierarchy Iterable → Collection → List/Queue/Set, Map is a separate branch and is not Iterable.
  • Variables and parameters are declared with an interface type; this way the implementation changes only in the new line.
  • Generic types catch the wrong type at compile time. The type argument is a reference type; primitive values are converted to wrappers by autoboxing and unboxing. Unboxing null throws a NullPointerException.
  • ArrayList is a dynamic array: get/set are O(1), appending at the end is amortized O(1), and insertion and removal in the middle are O(n). When the capacity is full, it grows by about 1.5 times; capacity is not size().
  • LinkedList is a doubly linked list: O(1) at the ends, get(i) O(n). In most cases ArrayList is the better choice.
  • Vector and Stack are old and synchronized. ArrayDeque is used for stacks and queues; push/pop/peek work at the front, offer at the back, poll at the front.
  • Queue operations have two forms: add/remove/element throw exceptions, offer/poll/peek return false/null.
  • PriorityQueue is a binary heap: add/poll O(log n), peek O(1). println(pq) prints the internal array and is not sorted; the elements must be Comparable or a Comparator must be given.
  • HashSet/HashMap are hash tables: the bucket is computed from hashCode and comparison within the bucket uses equals; O(1) on average, no order. LinkedHash… preserves insertion order; Tree… keeps order with a red-black tree and is O(log n).
  • Equal objects must have equal hash codes; a class that overrides equals also overrides hashCode. These fields of an object in a hashed collection are not modified.
  • TreeSet/TreeMap offer range queries; the rule is "start included, end excluded". In HashMap, put returns the old value, and get returns null for an absent key; Hashtable does not accept null.
  • The iterator is the mechanism behind for-each. Removal while traversing is done with it.remove() or removeIf; the list's own remove changes modCount and leads to ConcurrentModificationException.
  • Collections.sort is the stable TimSort (O(n log n)). The natural order is defined with Comparable.compareTo, other orders with Comparator; in comparisons Integer.compare is used, not subtraction. shuffle is Fisher–Yates; binarySearch works in O(log n) on a sorted list and returns −(insertion point) − 1 if it does not find the value.
  • A stream is a pipeline. The pipeline has a source, lazy intermediate operations (filter, map, sorted), and a terminal operation that runs the pipeline (collect, reduce, count). Elements pass through the pipeline one at a time; a stream is single-use; lambdas must be free of side effects, especially in parallel streams.
  • List.of/Set.of/Map.of produce an unmodifiable collection, Collections.unmodifiableList a read-only view, and List.copyOf an independent unmodifiable copy.

5.13Key terms

  • collection
  • Collections Framework
  • generics
  • type safety
  • wrapper class
  • autoboxing / unboxing
  • interface / implementation
  • list
  • dynamic array
  • linked list
  • index
  • stack
  • queue
  • priority queue
  • deque
  • set
  • hashing / hash table
  • hash code
  • map
  • iterator
  • natural ordering
  • comparator
  • anonymous class
  • lambda expression
  • shuffle
  • binary search
  • immutable
  • thread safety

5.14Test Yourself

  1. After the list List<Integer> l = new ArrayList<>(Arrays.asList(5, 6, 7)); is created, l.add(0, 4), l.remove(Integer.valueOf(6)), l.remove(2), and l.add(l.size(), 8) are applied in order. What are the list and l.indexOf(8)?

    Answer

    [4, 5, 6, 7] → the value 6 is removed: [4, 5, 7] → index 2 (7) is removed: [4, 5] → 8 at the end: [4, 5, 8]. indexOf(8) is 2.

  2. For an empty Deque<String> d = new ArrayDeque<>(), push("x"), offer("y"), push("z"), and addLast("w") are called in order. Then String a = d.pop(); String b = d.pollLast(); runs. What are d and a + b?

    Answer

    [x] → [x, y] → [z, x, y] → [z, x, y, w]. pop takes z from the front and pollLast takes w from the back. d = [x, y], a + b = "zw".

  3. Into the queue new PriorityQueue<Integer>(Collections.reverseOrder()), 7, 2, 9, 4 are added. What are the results of two poll() calls and the remaining size?

    Answer

    In reverse order the largest leaves first: 9, then 7. Two elements (2 and 4) remain in the queue.

  4. The characters of the string "banana" are counted in a TreeMap<Character, Integer> with merge(c, 1, Integer::sum). How is the map printed?

    Answer

    {a=3, b=1, n=2}. The letters are b-a-n-a-n-a: a occurs three times, n twice, and b once; TreeMap prints the keys in sorted order.

  5. A TreeSet contains the elements 15, 5, 25, 10, 20. What are headSet(15), subSet(10, 21), and tailSet(26)?

    Answer

    [5, 10] (15 excluded), [10, 15, 20] (10 included, 21 excluded), and [] (there are no elements at 26 or above).

  6. What does stream().filter(x -> x.length() > 3).map(x -> x.substring(0, 2)).sorted().collect(Collectors.toList()) produce on the list Arrays.asList("apple", "cherry", "plum", "fig", "pear")? What is mapToInt(String::length).sum()?

    Answer

    "fig" is eliminated; the first two letters of the rest are ap, ch, pl, pe, and once sorted the result is [ap, ch, pe, pl]. The sum of the lengths is 5 + 6 + 4 + 3 + 4 = 22.

  7. On the list [2, 3, 5, 8], if (x == 5) numbers.remove(x); is run inside a for-each. Is an exception thrown? What happens to the list?

    Answer

    No. When 5 (index 2) is removed, size becomes 3; cursor is already 3 and hasNext() returns false. The loop ends silently and 8 is never checked. The list is [2, 3, 8]. The code is faulty, but this data does not reveal it.

  8. What does Collections.binarySearch(Arrays.asList(2, 4, 6, 8, 10), 9) return?

    Answer

    9 is absent; it would have to go after 8 and before 10, that is, at index 4. The return value is −(4) − 1 = −5.

  9. A Student class overrides only equals. Two objects with the same fields are added to both an ArrayList and a HashSet, and contains is asked with the second object. Why do the results differ?

    Answer

    ArrayList.contains uses only equals and returns true. HashSet, on the other hand, first finds the bucket with hashCode. Because the hash codes inherited from Object are different, the two objects fall into different buckets; the set holds two elements and contains returns false. The fix is to write hashCode from the same fields.

5.15Further reading

  • Oracle, The Java Tutorials, the "Collections" and "Aggregate Operations" trails: they explain interfaces, implementations, algorithms, and stream pipelines step by step with official examples.
  • J. Bloch, Effective Java (3rd ed., Addison-Wesley, 2018), Items 11, 14, 45–48, and 64. It gives short, well-argued rules on hashCode, Comparable, the judicious and side-effect-free use of streams, and referring to objects by their interfaces.
  • M. Naftalin and P. Wadler, Java Generics and Collections (O'Reilly): a detailed examination of the internal structure of generics and the collection classes and the reasons behind their design.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals (12th ed., 2022), Chapter 9: covers collections together with the workings of hash tables, trees, and views.

5.16References

  • Oracle, The Java Tutorials: Collections (Interfaces, Implementations, Algorithms) and Generics.
  • Oracle, Java SE 21 API Documentation: the java.util package (Collection, List, Map, Collections…) and java.util.stream.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (4.5 Parameterized Types, 5.1.7 Boxing Conversion, 14.14.2 Enhanced for).
  • P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 16: Generic Collections).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly (Chapter 11: Data Structures).
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 9: Collections).
  • M. Naftalin and P. Wadler, Java Generics and Collections, O'Reilly.
  • J. Bloch, Effective Java, 3rd ed., Addison-Wesley (Item 11: always override hashCode when you override equals; Item 64: refer to objects by their interfaces).