The Plain Picture#
A warehouse with unlabelled boxes. Anyone can put anything in any box. When you open the box you expected to contain shoes, you find a fish — and you only find out when you try to wear it.
Labelled boxes — "SHOES ONLY" — are checked at the door: the fish is turned away before it gets in.
The Real Names#
Before Java 5 (2004), collections held plain Objects. That style still compiles — it's called a raw type — and shows the problem:
List raw = new ArrayList();
raw.add("Priya");
raw.add(200); // compiles fine — nothing stops a number going into a "list of names"
for (Object o : raw) {
String s = (String) o; // you must cast when reading...
}
// raw list: ClassCastException at runtime ← ...and it fails only when the program RUNSThe compiler even warns you:
warning: [unchecked] unchecked call to add(E) as a member of the raw type ListGenerics let you put a type parameter on a class or method — the label on the box:
List<String> names = new ArrayList<>();
names.add("Priya");
names.add(200); // compile error — rejected at the door
String first = names.get(0); // no cast neededTwo gains: errors move from run time to compile time, and casts disappear. (Never use raw types in new code.)
Check yourself
2 questionsWhat is a raw type, and why is it dangerous?
Show answerHide answer
A generic type used without its type parameter (List instead of List<String>); it accepts anything, so type mistakes appear only at
run time as ClassCastExceptions.
Name the two main benefits of generics.
Show answerHide answer
Type errors are caught at compile time; no casts when reading values.