Essay
Learning Java, Part 13: Generics and Collections
Study notes on generic classes and methods, type parameters, bounded types, wildcards and bounded wildcards, generic interfaces, raw types, the diamond operator, erasure and its restrictions, and the List, Set, Map and Queue collections with Comparable and Comparator. Written entirely by an AI model.
A Python list can hold anything, and you find out at runtime whether what you took out was the type you expected. Generics let a Java class be written once for any type while the compiler still checks every use. The handbook names generics as a CITS2005 topic. This part also covers the collections library, which the book leaves for a later volume but which every Java assignment uses.
A generic class
A type parameter in angle brackets stands for a type that the user of the class chooses:
class Box<T> {
private T item;
void put(T item) { this.item = item; }
T get() { return item; }
}
class Pair<K, V> {
final K key;
final V value;
Pair(K key, V value) { this.key = key; this.value = value; }
public String toString() { return key + "=" + value; }
}
public class Generic {
public static void main(String[] args) {
Box<String> b = new Box<>();
b.put("matcha");
String s = b.get(); // no cast needed
// b.put(42); // compile error
Pair<String, Integer> p = new Pair<>("cups", 3);
System.out.println(s.toUpperCase() + " " + p);
}
}
MATCHA cups=3
- Conventional names:
Ttype,Eelement,Kkey,Vvalue,Nnumber. new Box<>()uses the diamond operator: the compiler infers<String>from the variable’s type.- Type arguments must be reference types.
Box<int>is illegal; useBox<Integer>, and autoboxing (Part 12) converts for you. Box<String>andBox<Integer>are different types. You cannot assign one to the other.
Before generics, collections held Object, so every get needed a cast that could fail at runtime with ClassCastException. Generics move that failure to compile time.
Bounded types
<T extends Number> restricts T to Number or its subclasses, which lets the class call Number’s methods:
class Stats<T extends Number> {
private final T[] values;
Stats(T[] values) { this.values = values; }
double average() {
double sum = 0;
for (T v : values) sum += v.doubleValue(); // allowed by the bound
return sum / values.length;
}
}
public class Bounded {
public static void main(String[] args) {
System.out.println(new Stats<>(new Integer[] {1, 2, 3, 4}).average());
System.out.println(new Stats<>(new Double[] {1.5, 2.5}).average());
// new Stats<>(new String[] {"a"}); // compile error: String is not a Number
}
}
2.5
2.0
The word is always extends, even when the bound is an interface: <T extends Comparable<T>>. Several bounds join with &: <T extends Number & Comparable<T>>.
Generic methods
A method can have its own type parameters, written before the return type. The compiler infers them from the arguments:
import java.util.List;
public class Methods {
static <T extends Comparable<T>> T largest(List<T> items) {
T best = items.get(0);
for (T x : items) if (x.compareTo(best) > 0) best = x;
return best;
}
public static void main(String[] args) {
System.out.println(largest(List.of(3, 9, 4)));
System.out.println(largest(List.of("pear", "apple", "plum")));
}
}
9
plum
Constructors can be generic too, and so can interfaces: interface Container<T> { boolean contains(T x); }, implemented as class Bag<T> implements Container<T>.
Wildcards
Here is a surprise: List<Integer> is not a subtype of List<Number>, even though Integer is a subtype of Number. If it were, you could add a Double to a list of integers through the List<Number> reference. To write a method that accepts lists of any number type, use a wildcard:
| Wildcard | Accepts | You can |
|---|---|---|
List<?> |
a list of anything | read as Object |
List<? extends Number> |
List<Integer>, List<Double>… |
read as Number; not add |
List<? super Integer> |
List<Integer>, List<Number>, List<Object> |
add Integers |
import java.util.ArrayList;
import java.util.List;
public class Wild {
static double sum(List<? extends Number> nums) {
double s = 0;
for (Number n : nums) s += n.doubleValue();
return s;
}
static void addTens(List<? super Integer> out) {
out.add(10);
out.add(20);
}
public static void main(String[] args) {
System.out.println(sum(List.of(1, 2, 3)) + " " + sum(List.of(0.5, 0.25)));
List<Number> target = new ArrayList<>();
addTens(target);
System.out.println(target);
}
}
6.0 0.75
[10, 20]
The memory aid is PECS: producer extends, consumer super. A list you read from is a producer; a list you write to is a consumer.
Erasure and its restrictions
Generics exist only at compile time. The compiler checks the types and then erases them, replacing T with its bound (or Object) and inserting casts. At runtime, a Box<String> and a Box<Integer> are both just Box. This keeps compatibility with pre-generic code, and it explains the restrictions:
- You cannot create
new T()ornew T[10]: the runtime does not know whatTis. - A static field or method cannot use the class’s
T, because static members are shared by every parameterisation. - You cannot create an array of a generic type such as
new Box<String>[3]. - A generic class cannot extend
Throwable. x instanceof Box<String>is not allowed (you can only checkinstanceof Box<?>).- Two overloads that differ only in type arguments,
f(List<String>)andf(List<Integer>), clash after erasure. This is an ambiguity error.
A raw type is a generic class used with no type argument, such as List list = new ArrayList();. It exists for old code. It turns the checks off and gives “unchecked” warnings. Don’t write it.
The collections framework
java.util provides interfaces with several implementations each. Declare variables by the interface and choose the implementation once:
| Interface | Implementation | Python cousin | Notes |
|---|---|---|---|
List<E> |
ArrayList, LinkedList |
list | ordered, indexed, duplicates allowed |
Set<E> |
HashSet, LinkedHashSet, TreeSet |
set | no duplicates; TreeSet is sorted |
Map<K,V> |
HashMap, LinkedHashMap, TreeMap |
dict | keys unique; TreeMap sorted by key |
Queue<E>, Deque<E> |
ArrayDeque, PriorityQueue |
collections.deque, heapq |
FIFO, stack or priority |
import java.util.*;
public class Collections1 {
public static void main(String[] args) {
List<String> orders = new ArrayList<>(List.of("chai", "latte", "chai", "mocha"));
orders.add("latte");
orders.remove("mocha");
System.out.println(orders + " size " + orders.size());
Set<String> kinds = new TreeSet<>(orders);
System.out.println(kinds + " " + kinds.contains("chai"));
Map<String, Integer> counts = new TreeMap<>();
for (String o : orders) counts.merge(o, 1, Integer::sum);
System.out.println(counts + " " + counts.getOrDefault("flat white", 0));
for (Map.Entry<String, Integer> e : counts.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
System.out.println(stack.pop());
}
}
[chai, latte, chai, latte] size 4
[chai, latte] true
{chai=2, latte=2} 0
chai -> 2
latte -> 2
2
List.of,Set.ofandMap.of(Java 9) make immutable collections. Adding to one throwsUnsupportedOperationException, so wrap it innew ArrayList<>(...)when you need to change it.HashMapandHashSetrely onequalsandhashCode(Part 7). A class that overrides one without the other breaks them.- Removing from a list while looping over it with an enhanced
forthrowsConcurrentModificationException. Use anIteratorand itsremove()method, orlist.removeIf(...). remove(int index)andremove(Object o)are overloads, so on aList<Integer>,list.remove(1)removes the item at index 1, not the value 1.
Ordering: Comparable and Comparator
A class has a natural order if it implements Comparable<T>, whose compareTo returns a negative number, zero or a positive number. A Comparator gives any other order without changing the class:
import java.util.*;
public class Sorting {
record Student(String name, int mark) implements Comparable<Student> {
public int compareTo(Student o) { return name.compareTo(o.name); }
}
public static void main(String[] args) {
List<Student> s = new ArrayList<>(List.of(
new Student("Omar", 71), new Student("Ana", 85), new Student("Mei", 71)));
Collections.sort(s); // natural: by name
System.out.println(s.get(0).name());
s.sort(Comparator.comparingInt(Student::mark).reversed()
.thenComparing(Student::name)); // mark desc, then name
for (Student x : s) System.out.print(x.name() + " ");
System.out.println();
}
}
Ana
Ana Mei Omar
Exam-style checks
- What problem do generics solve? Show the same code with and without them.
- Why is
List<Integer>not a subtype ofList<Number>? How do wildcards help? - Explain type erasure and name two restrictions that follow from it.
- Write a generic method that returns the largest element of a list, with the bound it needs.
- When would you choose a
TreeMapover aHashMap?
Where to practise
Schildt’s Chapter 13 makes the queue from earlier parts generic. Do that, then write a word-frequency program that reads a text file (Part 10) into a Map<String, Integer> and prints the ten most common words using a Comparator. Finally, write a generic Stack<E> backed by an ArrayList<E> with push, pop, peek and isEmpty.