skip to content

What problem do generics solve in Java, and how did code work before them with Object and manual casts?

level: juniorimportance: must knowfreq 70%

answer

  1. when a type mistake gets caught
  2. containers that knew only Object
  3. a cast on every read
  4. the failure lands far from the bad add
  5. who writes the cast now?

basics

~20 s

Generics let a class state which type it works with, so the compiler rejects wrong types and reads need no written casts. Before Java 5, containers held Object, and a wrong cast failed only at run time.

solid answer

~40 s

Generics move type errors from run time to compile time. Before Java 5, a container meant for any element type stored `Object`: `add` took any object and `get` returned `Object`, so you wrote `(String) list.get(0)`. Nothing checked what went in, so a wrong element surfaced as a `ClassCastException` at a later read, possibly far from the faulty `add`. With `List<String>`, the compiler rejects `add(42)`, and `get` has type `String`. The cast has not vanished: the compiler inserts it, and `javap` shows the same instructions as the hand-written read. You also keep one reusable class instead of hand-writing `StringList` and `IntegerList`. The guarantee is a compile-time one, and the JLS ties it to the program raising no unchecked warnings, which raw types can trigger.

code

java · 28 lines
java
import java.util.ArrayList;
import java.util.List;

public class BeforeAndAfterGenerics {
    @SuppressWarnings({"rawtypes", "unchecked", "deprecation"})
    static void before() {
        List names = new ArrayList();           // raw: elements are Object
        names.add("Ada");
        names.add(new Integer(42));             // compiles: any Object fits
        String first = (String) names.get(0);   // a written cast on every read
        System.out.println(first);
        String second = (String) names.get(1);  // ClassCastException here
        System.out.println(second);
    }

    static void after() {
        List<String> names = new ArrayList<>();
        names.add("Ada");
        // names.add(42);                       // error: int cannot be converted to String
        String first = names.get(0);            // no written cast; javac emits a checkcast
        System.out.println(first);
    }

    public static void main(String[] args) {
        after();
        before();
    }
}

go deeper

for a junior

Recall the before and after: containers of Object with a cast on each read, then List<String> with the compiler rejecting wrong elements. Name ClassCastException as the failure that generics move to compile time.

for a middle

Explain that the cast survives in bytecode as a compiler-inserted checkcast, and that one generic declaration serves every reference type. Show why an old-style failure points at the read and not at the faulty add.

for a senior

When a ClassCastException appears on a line with no written cast, suspect heap pollution and look upstream for raw types and unchecked warnings. Treat those warnings as defects, and suppress one only where the reason is recorded.

for a principal

Weigh the compatibility choice: converting classes in place kept old callers compiling, at the cost of raw types and compile-time-only checks. A team's lever is the build, with -Xlint:unchecked and -Werror, migrating raw-typed module boundaries first.

## The problem: reuse without knowing the type A class such as a list should work for any element type, so its source cannot name just one. A **generic class** solves this by declaring a **type parameter**, as in `class ArrayList<E>`, and a **parameterized type** such as `List<String>` supplies the actual **type argument**. The compiler then checks uses of the class against that argument. The first release to support generics was Java 5, also written 1.5. Before that, one container for every class meant using `Object`, the superclass of all classes, and casting back on the way out. ## How code worked before generics ```java List names = new ArrayList(); names.add("Ada"); names.add(new Integer(42)); // compiles: any Object fits String first = (String) names.get(0); // a cast on every read String second = (String) names.get(1); // ClassCastException at run time ``` The `new Integer(42)` belongs to the era, because autoboxing arrived in the same release as generics. Today this form is called a **raw type**, and it still compiles. It has four costs: - **No check at insertion.** `add` accepts any object, so nothing stops the wrong element from going in. - **A cast on every read.** `get` returns `Object`, and each cast is a claim about the contents that the compiler takes on trust. - **Failure far from the cause.** The stack trace points at the read. The faulty `add` may be in another class and may have run long before. - **A contract in comments.** Only a comment or a variable name can say that this list holds strings. A developer could avoid casts by writing a `StringList` class with `add(String)` and `String get(int)`. That restores checking, but the same logic must be copied for each element type. An array such as `String[]` does name its element type, but it has a fixed length and offers none of the collection methods. ## What generics change | Aspect | `Object` and casts | `List<String>` | |---|---|---| | Adding a wrong element | Compiles | Compile error at that line | | Reading an element | `(String) names.get(0)` | `names.get(0)`, with type `String` | | Where a type mistake appears | `ClassCastException` at a read | `javac` error at the mistake | | Where the contract lives | A comment or a name | The declared type | | Reuse | One unchecked class, or one class per type | One declaration, any reference type | For `names.add(42)` on a `List<String>`, `javac` reports `incompatible types: int cannot be converted to String`. The mistake now stops the build, and it is reported where it was made. ## What generics do not change These points are where weak answers go wrong: - **The cast still runs.** `List.get` returns `Object` at run time, so for `String s = names.get(0);` the compiler emits a `checkcast`. `javap -c` shows identical instructions for that read and for a raw read with a written cast. Generics remove the cast from your source, not from the bytecode, so they are not a speed feature. - **The checks happen at compile time.** Type arguments are not reified at run time, and all parameterizations of a generic class share the same class at run time. How that works is covered with type erasure. - **The escape hatch remains.** The JLS allows raw types as a concession to compatibility with legacy code and strongly discourages them in new code. The difference between raw and parameterized types has its own question. - **The guarantee has a condition.** The JLS says a variable's value is compatible with its type as long as the program gives rise to no compile-time unchecked warnings. Adding `42` to a `List<String>` through a raw reference raises such a warning and creates **heap pollution**, where a variable of a parameterized type refers to an object that is not of that type. A later `String s = names.get(0);` then throws `ClassCastException` on a line with no written cast. - **Type arguments are reference types.** `List<int>` does not compile, so you write `List<Integer>`. ## Why the old style still compiles Existing classes were converted in place, which the JLS calls **generification**, so `List` became `List<E>`. Rejecting raw use would have invalidated large bodies of existing code and discouraged library authors from adopting generics, so a raw type may still be converted to a parameterized one, with an unchecked warning. That is why raw code from before Java 5 is not rejected for its raw types, and why a warning about them deserves attention and not a blanket suppression.

  • Why can a ClassCastException appear on a line with no cast, such as String s = names.get(0);?
    Because the compiler inserted a `checkcast` there. If a raw reference earlier added an `Integer` to that `List<String>`, the list is polluted, and the hidden cast fails at the read. The compiler reported the raw `add` as an unchecked call, but only as a warning, or a note without `-Xlint:unchecked`. So look upstream for raw types and suppressed warnings.
  • Do generics make collection code faster by removing casts?
    No. `List.get` still returns `Object` at run time, and a `checkcast` follows it, so `javap` shows the same instructions as a raw read with a written cast. The gain is earlier detection of mistakes and clearer signatures, not speed.
  • Arrays already named their element type before generics, so why was String[] not enough?
    An array has a fixed length and none of the collection methods, and each element type still needs its own code around it. Arrays do check stores at run time: writing an `Integer` through an `Object[]` alias of a `String[]` throws `ArrayStoreException`. Collections built on `Object` had no such element type to check.

  • Generics remove casts from the compiled bytecode as well as from the source.
  • Generics make collections faster because casting no longer happens at run time.
  • A List<String> checks each added element at run time and rejects wrong types.
  • Before generics, Java had no way to write one reusable collection class.
  • In old code, the ClassCastException is thrown by the add that stored the wrong element.
  • Raw types were removed when generics arrived, so old code had to be rewritten.

Generics
Java 1.5

Assumes JDK 27; generics first shipped in Java 5 (1.5), and the raw style from before them still compiles at 27.

context