List<String> and List<Integer> are the same class, List, filled in with a different type. That's generics: a class or method with a type parameter in angle brackets, which the user chooses. The compiler then checks every use, so you can't put a number into a list of strings, and you don't need casts to get things out.
You can write your own. Here Box<T> holds one thing of any type T; T is just a placeholder name (single capitals are the habit: T for type, K and V for key and value, E for element).
Java
public class Main {
static class Box<T> {
private final T item;
Box(T item) { this.item = item; }
T get() { return item; }
boolean isEmpty() { return item == null; }
}
record Pair<A, B>(A first, B second) {}
public static void main(String[] args) {
Box<String> word = new Box<>("duck");
Box<Integer> number = new Box<>(42);
System.out.println(word.get().toUpperCase());
System.out.println(number.get() + 1);
Pair<String, Integer> p = new Pair<>("age", 12);
System.out.println(p.first() + "=" + p.second());
}
}
Prints
DUCK
43
age=12
A method can have its own type parameter, written before the return type. This one works on a list of anything:
Java
public class Main {
static <T> T last(List<T> xs) {
return xs.get(xs.size() - 1);
}
static <T> List<T> repeat(T x, int n) {
List<T> out = new ArrayList<>();
for (int i = 0; i < n; i++) out.add(x);
return out;
}
public static void main(String[] args) {
System.out.println(last(List.of("a", "b", "c")));
System.out.println(last(List.of(1, 2, 3)) * 10);
System.out.println(repeat("hi", 3));
}
}
Prints
c
30
[hi, hi, hi]
Sometimes a method needs to know a bit about T, for example that items can be compared. <T extends Comparable<T>> says "any type that can be compared with itself", which lets the method call compareTo.
Sorting with Comparable
Java can sort numbers and strings because they know their own order. To sort your own class, give it a natural order by implementing Comparable and its one method, compareTo. It returns a negative number if this object comes first, positive if the other does, and 0 if they're equal. Integer.compare(a, b) does that sum for you safely.
Java
public class Main {
record Student(String name, int score) implements Comparable<Student> {
public int compareTo(Student other) {
return Integer.compare(score, other.score);
}
}
public static void main(String[] args) {
List<Student> all = new ArrayList<>(List.of(
new Student("Ana", 91), new Student("Ben", 78), new Student("Cy", 85)));
Collections.sort(all);
for (Student s : all) System.out.println(s.name() + " " + s.score());
System.out.println(Collections.max(all).name());
}
}
Prints
Ben 78
Cy 85
Ana 91
Ana
Sorting with Comparator
Often you want more than one order: by score for a leaderboard, by name for a register. A Comparator is an order kept outside the class. The neat way to make one is Comparator.comparing, given what to sort by; .reversed() flips it and .thenComparing breaks ties. (Student::name means "each student's name"; the Advanced Java course explains that :: syntax.)
Java
public class Main {
record Student(String name, int score) {}
public static void main(String[] args) {
List<Student> all = new ArrayList<>(List.of(
new Student("Cy", 85), new Student("Ana", 91), new Student("Ben", 85)));
all.sort(Comparator.comparing(Student::name));
System.out.println(all.get(0).name());
all.sort(Comparator.comparing(Student::score).reversed().thenComparing(Student::name));
for (Student s : all) System.out.println(s.name() + " " + s.score());
}
}
Prints
Ana
Ana 91
Ben 85
Cy 85
Ben and Cy both scored 85, so thenComparing(Student::name) puts them in name order. Sorting in Java is stable: items that compare equal keep the order they were in.
Never write compareTo as a - b with big numbers: the subtraction can overflow and flip the sign. Integer.compare(a, b) is always right.
Practice
What does the T in class Box<T> stand for?
More info
Quick reference
class Box<T>
A generic class; T is chosen by the user: Box<String>.
static <T> T m(List<T> xs)
A generic method.
<T extends Comparable<T>>
T must be comparable with itself.
implements Comparable<X>
A natural order: compareTo(other) < 0 means this first.