Sub topic 2
Typed Collections with Generics
In the last chapter you met the Collection interface and its family: List, Set, and Map. Before you use any of them, you need one more tool. It is called generics, and it lets you tell Java what kind of thing a collection will hold.
This chapter explains what generics are, why they matter, and how to write them. You will also learn the diamond operator, a short form that saves typing.
The Problem Generics Solve
A collection is a container. Picture a box. If you don't label the box, anyone can drop anything into it. Later, when you reach in, you can't be sure what you will pull out.
Early versions of Java (before Java 5, released in 2004) worked like this. A list could hold any object at all. Code that uses a collection with no type label is called a raw type. A raw type is a generic class used without its type information.
Here is what can go wrong with a raw type:
import java.util.ArrayList;
import java.util.List;
public class RawTypeDemo {
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
List items = new ArrayList(); // raw type: no label
items.add("hello");
items.add(42); // Java allows this
String first = (String) items.get(0);
System.out.println(first); // hello
String second = (String) items.get(1); // crashes here
System.out.println(second);
}
}This program compiles. Then it crashes while running, with a ClassCastException. A cast is code like (String) that tells Java "trust me, this object is a String." Here the object was really an Integer, so the cast fails.
There are two problems:
- You must write a cast every time you read an element.
- Mistakes show up only when the program runs, possibly long after the bad value went in.
What a Generic Type Looks Like
Generics fix both problems. A type parameter is a type written inside angle brackets < > that says what a collection holds. You read List<String> as "list of String."
import java.util.ArrayList;
import java.util.List;
public class GenericDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
// names.add(42); // compile error: int cannot be converted to String
String first = names.get(0); // no cast needed
System.out.println(first); // Ana
System.out.println(first.toUpperCase()); // ANA
}
}Now the label is on the box. Java checks every add call against it. If you remove the // in front of names.add(42), the program will not compile at all. The mistake is caught before the program ever runs.
Reading is easier too. names.get(0) already returns a String, so you can call String methods like toUpperCase() straight away.
Reading the Parts of a Declaration
Look at this line piece by piece:
List<String> names = new ArrayList<>();| Part | Meaning |
|---|---|
| `List` | The interface type of the variable |
| `<String>` | The type parameter: what the list holds |
| `names` | The variable name |
| `new ArrayList` | The actual class that does the work |
| `<>` | The diamond operator: "use the same type as the left side" |
The Diamond Operator
Before Java 7, you had to write the type on both sides:
List<String> names = new ArrayList<String>();That repeats String for no good reason. The compiler can already see it on the left. So Java 7 added the diamond operator, an empty pair of angle brackets <>. It tells the compiler to work out the type for you. The name comes from its shape.
Both lines below create exactly the same list:
List<String> longForm = new ArrayList<String>();
List<String> shortForm = new ArrayList<>();The saving grows when types get longer. A Map has two type parameters: one for the key and one for the value. Here is a map from a name to a list of scores:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DiamondDemo {
public static void main(String[] args) {
// Without the diamond you would repeat <String, List<Integer>>
Map<String, List<Integer>> scores = new HashMap<>();
List<Integer> anaScores = new ArrayList<>();
anaScores.add(90);
anaScores.add(85);
scores.put("Ana", anaScores);
System.out.println(scores); // {Ana=[90, 85]}
}
}You will learn Map properly in a later chapter. For now, notice two things. A type can have more than one parameter, separated by a comma. Type parameters can also be nested, like List<Integer> inside a Map.
Declare with the Interface, Create with the Class
You may wonder why the left side says List but the right side says ArrayList. List is an interface: a list of methods a class promises to provide. ArrayList is one class that keeps that promise.
Writing the variable as List<String> means the rest of your code depends only on list behavior. If you later want a different kind of list, you change one word:
List<String> names = new ArrayList<>();
// later, if needed:
// List<String> names = new LinkedList<>();Nothing else in your program has to change. This habit also works in method parameters:
import java.util.ArrayList;
import java.util.List;
public class LengthDemo {
static int totalLength(List<String> words) {
int total = 0;
for (String w : words) {
total += w.length();
}
return total;
}
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("cat");
words.add("horse");
System.out.println(totalLength(words)); // 8
}
}The method totalLength accepts any List<String>. Inside it, Java knows every element is a String, so w.length() is safe.
Common Mistakes
Beginners hit the same few errors with generics. Here they are with their fixes.
| Mistake | What happens | Fix |
|---|---|---|
| `List<int> nums` | Compile error: "unexpected type" | Use the wrapper type: `List<Integer>` |
| `new ArrayList()` with no brackets | Raw type; compiler warning; unsafe | Write `new ArrayList<>()` |
| `List<String> x = new ArrayList<Integer>();` | Compile error: incompatible types | Make both sides match, or use `<>` |
| `var list = new ArrayList<>();` | List of `Object`; you lose the type check | Write `var list = new ArrayList<String>();` |
Why Not `List<int>`?
Type parameters must be reference types, meaning class types like String or Integer. Primitive types like int, double, and boolean are not allowed. Java gives each primitive a matching class, called a wrapper type. Integer wraps int. The next chapter covers how Java converts between them for you.
The `var` Trap
The keyword var (Java 10 and later) lets the compiler guess a variable's type from the right side. If you combine var with an empty diamond, the compiler has no type to copy. It falls back to Object, the most general type, and the list will accept anything:
import java.util.ArrayList;
public class VarDemo {
public static void main(String[] args) {
var loose = new ArrayList<>(); // ArrayList<Object>
loose.add("text");
loose.add(3.14); // allowed, no check
var strict = new ArrayList<String>(); // ArrayList<String>
strict.add("text");
// strict.add(3.14); // compile error
System.out.println(loose); // [text, 3.14]
System.out.println(strict); // [text]
}
}Generics Exist Only at Compile Time
One more fact will help you later. The type check happens when you compile. When the program runs, Java mostly forgets the type parameters. A List<String> and a List<Integer> become the same kind of object in memory. This is called type erasure.
For a beginner, the practical lesson is simple. Generics are a safety check the compiler does for you. Respect the compiler's warnings, because once the program is running, nothing else checks the types.
Summary
- Generics put a type label on a collection, such as
List<String>. - The compiler rejects wrong types, and you never need casts when reading.
- The diamond
<>copies the type from the left side. - Declare variables with the interface (
List), create them with a class (ArrayList). - Type parameters must be classes, so use
Integerinstead ofint.
Exercise
This line does not compile: List<double> prices = new ArrayList<>();. Why not, and how do you fix it?
Show answer
Type parameters must be reference (class) types, and double is a primitive. Use the wrapper class instead: List<Double> prices = new ArrayList<>();.
Exercise
Rewrite Map<String, List<String>> groups = new HashMap<String, List<String>>(); using the diamond operator.
Show answer
Map<String, List<String>> groups = new HashMap<>(); The compiler copies <String, List<String>> from the left side.
Exercise
A teammate writes var cities = new ArrayList<>(); and then adds both "Paris" and 75. The code compiles. Explain why, and give a line that would make the compiler reject the number.
Show answer
With an empty diamond and var, the compiler has no type to copy, so it uses ArrayList<Object>, which accepts any object. Write var cities = new ArrayList<String>(); or List<String> cities = new ArrayList<>();. Then cities.add(75) is a compile error.
Exercise
What is the main advantage of finding a type mistake at compile time instead of getting a ClassCastException at run time?
Show answer
The compiler stops you before the program runs and points to the exact line where the wrong value goes in. A ClassCastException appears only when that code runs, maybe much later and far from where the wrong value was added, so it is harder to find and can reach users.