Sub topic 2
Typed Collections with Generics
A collection holds many objects. Java needs to know what kind of objects those are. Generics let you tell it.
What a Type Parameter Is
A type parameter is a type you write inside angle brackets, < >, after the name of a class or interface. It tells Java what the collection will hold.
List<String>is a list that holds onlyStringobjects.Set<Double>is a set that holds onlyDoubleobjects.Map<String, Integer>is a map withStringkeys andIntegervalues. A map takes two type parameters.
A generic type is a class or interface that takes type parameters, such as List<E>. The letter E stands in for "element type". You replace it with a real type when you use it.
Why Generics Matter
Without generics, a list can hold anything. When you read an item back, Java only knows it is an Object. You must cast it, which means telling Java "trust me, this is a String". If you are wrong, the program crashes while it runs.
With generics, the compiler checks your code before it runs. The compiler is the tool that turns your Java source into a program. If you try to put a number into a List<String>, the compiler stops you with an error. That turns a crash at run time into an error you see right away.
The Diamond Operator
When you create a collection, you could write the type twice:
List<String> names = new ArrayList<String>();That repeats itself. The diamond operator is the empty pair <>. It tells Java to copy the type from the left side:
List<String> names = new ArrayList<>();Both lines do the same thing. Most Java code uses the shorter one.
A Worked Example
This program builds a typed list and reads from it without any casts.
import java.util.ArrayList;
import java.util.List;
public class GenericsDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
String first = names.get(0); // no cast needed
System.out.println(first.toUpperCase()); // ANA
// names.add(42); // would not compile: 42 is not a String
System.out.println(names.size()); // 2
}
}Run it and you will see ANA and then 2. Remove the // in front of names.add(42); and try to compile. The compiler refuses, because 42 is an int, not a String.
Raw Types: A Common Mistake
A raw type is a generic type used without angle brackets, like List names = new ArrayList();. Older code still does this, so it compiles, but the compiler only gives you a warning and checks nothing. Avoid raw types in new code.
| You write | Meaning |
|---|---|
| `List<String> a = new ArrayList<>();` | Typed list, checked by the compiler |
| `List<String> a = new ArrayList<String>();` | Same, longer form |
| `List a = new ArrayList();` | Raw type, no checking (avoid) |
| `List<int> a` | Compile error, use `Integer` |
Exercise
Write one line that declares a variable called prices as a List of Double and creates an empty ArrayList for it, using the diamond operator.
Show answer
List<Double> prices = new ArrayList<>();
Exercise
A list is declared as List<String> words = new ArrayList<>(); What happens if you write words.add(3.5); and why?
Show answer
The code does not compile. The type parameter says the list holds only String objects, and 3.5 is a double, so the compiler reports an error before the program runs.