Sub topic 1
Why Generics Exist
Every value in Java has a type. A type is a label that says what kind of value something is, such as String, Integer, or List. The type tells Java which actions are allowed on the value.
Java checks types at two different moments:
- Compile time is when the
javaccompiler turns your source code into class files. Errors found here stop the build, so they never reach users. - Runtime is when the Java Virtual Machine actually runs your program. Errors found here crash the program while it is working.
Catching a mistake at compile time is cheaper and safer than finding it at runtime. Generics exist to move a whole family of mistakes from runtime to compile time. This chapter shows that family of mistakes and how generics fix it.
Life Before Generics
Generics were added in Java 5, in 2004. Before that, collections like ArrayList could hold any object at all. A list did not know or care what you put inside it.
A list used this way is called a raw type. A raw type is a generic class used without saying what type it holds. Today you can still write raw types, but you should not. Here is why.
The cast problem
A list without a declared element type hands back every element as Object. Object is the parent type of every class in Java. To use an element as a String, you must cast it. A cast is an instruction like (String) x that tells the compiler, "Trust me, this value is really a String."
The compiler does trust you. It does not check the claim. The check happens later, at runtime.
A worked example
Save this as RawListDemo.java:
import java.util.ArrayList;
import java.util.List;
public class RawListDemo {
public static void main(String[] args) {
List list = new ArrayList(); // raw type
list.add("hello");
list.add(42); // compiles: anything can go in
String first = (String) list.get(0); // cast required
String second = (String) list.get(1); // ClassCastException at runtime
}
}Compile and run it:
javac RawListDemo.java
java RawListDemoThe compiler accepts the code. It only prints a note that the file "uses unchecked or unsafe operations." Then the program crashes with an error like this:
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.StringA ClassCastException is the error Java throws when a cast turns out to be false. Here, the second element is the number 42, not a String.
Walk through what happened, line by line:
list.add("hello")puts aStringin the list. Fine.list.add(42)puts anIntegerin the list. The compiler allows it, because a raw list accepts anything.(String) list.get(0)works, because element 0 really is aString.(String) list.get(1)fails, because element 1 is anInteger.
The real bug is on line 2, where the wrong value went in. The crash happens on line 4, where the value came out. In a small program these lines sit next to each other. In a large program, the bad add might be in a different class, written by a different person, months earlier. The crash points you to the wrong place.
The Same Code with Generics
Now give the list an element type. You write the type in angle brackets: List<String>. Read it as "list of String."
import java.util.ArrayList;
import java.util.List;
public class GenericListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hello");
// list.add(42); // compile error: int cannot be converted to String
String first = list.get(0); // no cast needed
System.out.println(first.toUpperCase());
}
}This program compiles cleanly and prints HELLO. Three things changed:
- The wrong value cannot go in. If you remove the
//beforelist.add(42), the compiler refuses to build the program. The bug is caught on the exact line that caused it. - No cast is needed.
list.get(0)already returns aString, because the compiler knows what the list holds. - The code documents itself. Anyone who reads
List<String>knows what the list contains without hunting through the code.
The String inside the angle brackets is called a type argument. It fills in a blank that the List interface leaves open. That blank is called a type parameter. You will write your own type parameters in the next chapter.
Why Not Just Write One Class per Type?
Before generics, programmers who wanted safety had another option: write a separate class for each type. Imagine a simple container that holds one value.
public class StringBox {
private String value;
public StringBox(String value) { this.value = value; }
public String get() { return value; }
}
class IntegerBox {
private Integer value;
public IntegerBox(Integer value) { this.value = value; }
public Integer get() { return value; }
}Each class is type safe. But the two classes are the same code with one word changed. You would need a DoubleBox, a CustomerBox, an OrderBox, and so on. Every bug fix would have to be copied into each one.
The other option was one class that stores Object:
public class ObjectBox {
private Object value;
public ObjectBox(Object value) { this.value = value; }
public Object get() { return value; }
}This is one class for every type, but it brings back the cast problem. Callers must write (String) box.get() and hope they are right.
So before generics you had to choose between two bad options:
| Approach | Reusable for many types? | Checked by the compiler? | Casts needed? |
|---|---|---|---|
| One class per type (`StringBox`) | No | Yes | No |
| One class using `Object` | Yes | No | Yes |
| Generic class (`Box<T>`) | Yes | Yes | No |
Generics give you the last row. You write the code once, and the compiler still checks every use.
What Generics Do Not Change
Generics are a compile-time tool. They help the compiler catch mistakes, but they do not add new checks while the program runs. If you mix generic and raw code, the compiler can no longer protect you. That is why the compiler prints the "unchecked or unsafe operations" note you saw earlier. You will learn how those warnings work, and how Java removes type arguments when it compiles, in the chapters on type erasure and raw types.
Summary
- A raw type such as
Listaccepts any object and returnsObject, so you must cast. - A wrong cast fails only at runtime, with a
ClassCastException, often far from the real bug. - A generic type such as
List<String>lets the compiler reject wrong values and removes the need for casts. - Generics let you write one class that works for many types while staying type safe.
Exercise
The code List list = new ArrayList(); list.add(3.14); String s = (String) list.get(0); compiles. What happens when it runs, and which line holds the real mistake?
Show answer
It throws a ClassCastException on the cast, because the element is a Double, not a String. The real mistake is the add call, which put a Double into a list that the code later treats as holding Strings.
Exercise
Rewrite the declaration List names = new ArrayList(); so that the compiler rejects names.add(42) and names.get(0) returns a String without a cast.
Show answer
Declare it as List<String> names = new ArrayList<String>();. The type argument String tells the compiler the list holds only Strings, so adding 42 is a compile error and get returns a String directly.
Exercise
Before Java 5, a team wrote StringBox, IntegerBox, and DoubleBox classes with identical code. What problem does this cause, and what problem would they face if they replaced all three with one ObjectBox?
Show answer
Separate classes duplicate code, so every change must be made in each copy. A single ObjectBox removes the duplication but loses compile-time checking, so callers must cast the result and can get a ClassCastException at runtime. A generic Box class solves both problems.