ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Why Type Erasure Exists
Book 1 · Volume II — Generics, Collections & Type System · Topic 3.1

Why Type Erasure Exists

Backward compatibility and how generic code is compiled

11 min readStage 1 · Foundations14 interview questions
Prerequisites
Chapter 1
Covers
Backward compatibility · Generic compilation
Related
3.2 Erasure Behavior · 3.3 Restrictions
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Type erasure is the strategy by which Java implements generics: the compiler uses type arguments for checking, then removes them, so the bytecode and the JVM work with ordinary non-generic types. Generics were added in Java 5 (2004) to a platform with a huge installed base of non-generic code; erasure was chosen so that old and new code could interoperate without change.

2Why It Exists

By 2004 Java had been in production for eight years. The collections framework of Java 1.2 was used everywhere with Object elements, millions of compiled class files depended on its method signatures, and libraries shipped as binaries that their users could not recompile. Any design for generics had to let a library adopt them without forcing its clients to change, and let a client adopt them while still using libraries that had not.

The design came from research rather than from scratch. Generic Java (GJ), by Gilad Bracha, Martin Odersky, David Stoutamire and Philip Wadler in 1998, showed that generics could be compiled by erasure onto the existing JVM, with the old collection classes reused rather than replaced. JSR 14 adopted that approach for Java 5. The alternative, run-time type arguments, would have needed new JVM features and a second set of collection classes, and every library would have faced a choice between its old and its new users.

3Core Concepts

Backward compatibility

The design goal was migration compatibility: existing binaries compiled for Java 1.4 had to keep running, libraries had to be able to adopt generics without forcing all their clients to recompile, and the collections API could not be duplicated into generic and non-generic versions. Because a generic List<Order> erases to the same java.util.List that old code used, both can call each other directly. The JVM itself needed no changes.

Old and new code share the same erased types
Figure 1 — Old and new code share the same erased types

The alternative — reified generics, as in C#, where List<int> and List<string> are distinct run-time types — would have required new JVM features and parallel collection APIs. Java accepted the limitations of erasure (3.3) as the price of a smooth migration.

Generic compilation

javac processes generic code in stages: it type-checks all uses of generic types, erases type arguments and replaces type parameters with their leftmost bound (or Object), inserts casts where erased values are used as specific types, and generates bridge methods where needed (3.2). Generic declarations are still recorded in the class file's Signature attribute, so tools and reflection can read them.

The javac pipeline for generic code
Figure 2 — The javac pipeline for generic code

4How It Works Internally

Java 5 added generics without giving the JVM any generic semantics. The class-file format gained the Signature attribute, which stores the generic form of a class, field or method declaration as metadata, and bridge methods were marked with the ACC_BRIDGE flag; the verifier and the interpreter ignore both. Method and field descriptors, which are what the JVM uses to link a call, contain only erased types, so List<Order> findAll() and the old List findAll() have the same descriptor, ()Ljava/util/List;.

javac checks and erases; the JVM runs erased code; reflection reads the declarations
Figure 3 — javac checks and erases; the JVM runs erased code; reflection reads the declarations

Figure 3 shows who sees what. Because the descriptors did not change, a class compiled for Java 1.4 links against a generic library, and a generic class links against an old one, with unchecked warnings at compile time as the only trace. The reflection API grew a new Type hierarchy so that frameworks could read the Signature attribute.

5APIs / Features / Syntax

Erasure is not something you call, but three tools expose it: the compiler's warnings, javap, and the reflection types that represent what the Signature attribute keeps.

Tool or typeWhat it shows
javac -Xlint:unchecked -Xlint:rawtypesEvery place where erasure means the compiler can no longer guarantee type safety
javap -s, javap -vErased descriptors (-s) and the Signature attribute with the generic form (-v)
ParameterizedTypeA type with arguments, such as List<T> or List<Order>
TypeVariableA type parameter such as T, with its bounds
WildcardType? extends T or ? super T
GenericArrayTypeAn array of a generic type, such as T[] or List<String>[]

For an interface Repository<T> with the methods List<T> findAll(), Map<String, ? extends T> index() and T[] page(), reflection returns one of each kind:

JAVAReflectTypes.java
Class<?> repo = Repository.class;
// List<T>: a ParameterizedType
Type t = repo.getMethod("findAll").getGenericReturnType();
// T: a TypeVariable
Type arg = ((ParameterizedType) t).getActualTypeArguments()[0];
// ? extends T: a WildcardType
Type idx = repo.getMethod("index").getGenericReturnType();
Type w = ((ParameterizedType) idx).getActualTypeArguments()[1];
// T[]: a GenericArrayType
Type arr = repo.getMethod("page").getGenericReturnType();
OUTPUT
ParameterizedType: java.util.List<T>
TypeVariable: T
WildcardType: ? extends T
GenericArrayType: T[]

6Practical Examples

Example 1 — Mini program: old and new code calling each other

Problem. The goal of erasure was that code written for Java 1.4 and generic code could call each other without adapters. This program puts both styles side by side: a Legacy class that uses only raw types, and generic code that consumes and feeds it.

JAVALegacyInterop.java
public class LegacyInterop {
    // "Java 1.4" code: raw types only
    @SuppressWarnings({"rawtypes", "unchecked"})
    static class Legacy {
        static List loadNames() {
            List names = new ArrayList();
            names.add("ann");
            names.add("bob");
            return names;
        }
        static int countLongerThan(List items, int n) {
            int count = 0;
            for (Iterator it = items.iterator(); it.hasNext(); )
                if (((String) it.next()).length() > n) count++;
            return count;
        }
    }
 
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void main(String[] args) {
        List<String> names = Legacy.loadNames();     // unchecked conversion
        names.add("christopher");                    // new code, fully checked
        System.out.println(names + " " + names.getClass().getName());
        System.out.println("longer than 3: "
                + Legacy.countLongerThan(names, 3));
        // the same class serves both worlds: no copies, no adapters
        List raw = names;
        System.out.println("same object: " + (raw == names));
    }
}
OUTPUT
[ann, bob, christopher] java.util.ArrayList
longer than 3: 1
same object: true

Why it behaves this way. loadNames() returns a raw List, and assigning it to List<String> is an unchecked conversion: legal, with a warning, because the compiler cannot verify the elements. From then on the generic code is fully checked. The same object goes back into countLongerThan, which casts each element to String as pre-generics code always did. There is one ArrayList class and one object; no wrapper, copy or second collection type is needed, which is exactly what reified generics would not have allowed.

Example 2 — Raw and generic methods share one descriptor

Problem. Section 4 says that a generic signature and its raw form link identically. This program asks reflection for both.

JAVASameDescriptor.java
public class SameDescriptor {
    @SuppressWarnings("rawtypes")
    static int rawSize(List items) { return items.size(); }
 
    static <T> int genericSize(List<T> items) { return items.size(); }
 
    public static void main(String[] args) throws Exception {
        for (String name : List.of("rawSize", "genericSize")) {
            Method m = SameDescriptor.class.getDeclaredMethod(name, List.class);
            System.out.println(name + ": parameter "
                    + m.getParameterTypes()[0].getName()
                    + ", declared " + m.getGenericParameterTypes()[0]);
        }
        System.out.println(rawSize(List.of(1, 2)) + genericSize(List.of("a")));
    }
}
OUTPUT
rawSize: parameter java.util.List, declared interface java.util.List
genericSize: parameter java.util.List, declared java.util.List<T>
3

Why it behaves this way. Both methods are found with getDeclaredMethod(name, List.class), because their erased parameter type is java.util.List. Only the declared, generic view differs: getGenericParameterTypes() reads List<T> from the Signature attribute of genericSize, while rawSize has none and reports the plain interface. This is why a library could add type arguments to its methods in Java 5 without breaking a single compiled caller.

Example 3 — What survives: declarations, not objects

Problem. Erasure is often summarised as "generic types are lost at run time". This program shows which parts are lost and which are kept.

JAVAKeptTypes.java
public class KeptTypes {
    record Order(long id) {}
 
    // a named subclass fixes the type argument in its declaration
    @SuppressWarnings("serial")
    static final class OrderList extends ArrayList<Order> {}
 
    static List<Order> pending = new ArrayList<>();
 
    public static void main(String[] args) throws Exception {
        var sup = (ParameterizedType) OrderList.class.getGenericSuperclass();
        System.out.println("OrderList extends " + sup.getTypeName());
        System.out.println("field pending:    "
                + KeptTypes.class.getDeclaredField("pending").getGenericType());
        System.out.println("an ArrayList:     "
                + new ArrayList<Order>().getClass().getGenericSuperclass());
    }
}
OUTPUT
OrderList extends java.util.ArrayList<KeptTypes$Order>
field pending:    java.util.List<KeptTypes$Order>
an ArrayList:     java.util.AbstractList<E>

Why it behaves this way. OrderList declares ArrayList<Order> as its superclass, and the field declares List<Order>; both declarations are stored in the class file, so reflection returns them with Order included. A plain new ArrayList<Order>() has no declaration of its own, so the best reflection can do is the generic superclass of ArrayList itself, AbstractList<E>. Frameworks rely on the first behaviour: a named subclass or an anonymous type token carries its type arguments (3.2).

7Common Problems & Mistakes

MisconceptionConsequenceBetter approach
"Erasure makes generics unsafe"Teams distrust generic code or add defensive castsThe compile-time guarantee holds whenever there are no unchecked warnings; keep the count at zero
"All generic information is lost at run time"Developers miss that frameworks can read declared types, or build fragile workaroundsRead declarations through reflection; pass Class<T> or type tokens for objects (Example 3)
"Raw types are fine, the bytecode is the same anyway"Type checking is switched off and heap pollution followsRaw types are for pre-Java 5 interoperation only
"Generics cost run-time performance"Premature rewrites into arrays or Object-based codeErased code is the same as hand-written casts; measure boxing instead
"Changing List to List<Order> breaks callers"Libraries keep raw signatures for yearsAdding type arguments keeps the descriptor (Example 2); changing bounds does not

8Performance & Production Considerations

Erasure itself has no run-time cost: there is one class per generic type, so no code duplication, and the casts javac inserts are cheap and often removed by the JIT. Its indirect costs are boxing, because primitives cannot be type arguments, and the late ClassCastException of heap pollution, which shows up at an inserted cast far from the faulty write (3.2).

For production releases, the erased descriptor is the binary contract of a generic API. Type arguments can be added or changed freely without breaking compiled callers, but changing a bound, or the order of bounds, changes the erasure and leads to NoSuchMethodError in code that was not recompiled. Binary-compatibility checkers such as japicmp report exactly these changes.

9Architecture & Design Considerations

Erasure is a textbook architecture trade-off: the Java team accepted permanent limitations in expressiveness (3.3) in exchange for migrating an entire ecosystem without a flag day. C# made the opposite choice a year later, with reified generics in .NET 2.0 and a second, generic collection library beside the old one. Both decisions were reasonable for their platforms, and both still shape everyday code two decades later (Figure 4).

Erasure and reification: the same problem, two answers
Figure 4 — Erasure and reification: the same problem, two answers

The lesson carries over to any platform change: list the compatibility guarantees first, binary, source and behavioural, decide which ones the migration must keep, and accept the design that keeps them even when a cleaner one exists. Project Valhalla follows the same rule, adding value types to Java without breaking erased generic code.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is type erasure?

The compiler's removal of generic type arguments after type checking: parameterised types become their raw types, type parameters become their bounds, and casts are inserted where needed. The type arguments exist only for the compiler, which uses them to check every use and to insert casts; the JVM runs ordinary non-generic code.

Q2L2 · IntermediateTrade-off

Why did Java choose erasure instead of reified generics?

For migration compatibility: existing non-generic binaries and libraries had to interoperate with new generic code without recompilation or duplicated APIs, and without changes to the JVM. Erased generic signatures have the same descriptors as the raw ones, so old and new code link against each other (Example 1). Reified generics would have required JVM changes and a second collections library, as C# chose.

Q3L3 · Senior EngineerInternals

Does type erasure mean all generic information is lost?

No. Generic declarations of classes, fields, methods and supertypes are kept in the class file's Signature attribute and are available through reflection. What is lost are the type arguments of individual objects at run time. This is how frameworks recover types from fields, method signatures and type tokens (Example 3).

Q4L3 · Senior EngineerTrade-off

What is the long-term cost of the erasure decision?

Restrictions such as no generic array creation, no instanceof with type arguments unless the compiler can prove the test safe, no primitives as type arguments, and boxing overhead for numeric collections. Project Valhalla aims to address some of these without breaking compatibility. The benefit was a migration without breaking a single binary, and most teams never notice the cost outside of arrays, numeric collections and framework code.

Q5L1 · BasicConcept

What does migration compatibility mean in the design of Java generics?

That generic and pre-generic code can be mixed in any order of adoption: a library can add generics before its clients, or clients before their libraries, and everything keeps compiling and running. Erasure achieves it because a generic signature erases to the same descriptor as the raw one, so the JVM links them identically. The price is that type arguments are not available at run time.

Q6L2 · IntermediateCode

What does this program print?

JAVAErasureQuiz.java
public class ErasureQuiz {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>();
        List<Integer> b = new LinkedList<>();
        List<Integer> c = new ArrayList<>();
        System.out.println(a.getClass() == c.getClass());
        System.out.println(b.getClass() == c.getClass());
        System.out.println(a.getClass().getTypeParameters()[0]);
    }
}

It prints true, then false, then E. a and c are both ArrayList objects, whatever their type arguments, so their classes are identical; b is a LinkedList, a different class. getTypeParameters() returns the declaration's type variable, E from ArrayList<E>, not the String the object was created with, which is lost.

Q7L2 · IntermediateInternals

What is the Signature attribute, and does the JVM use it?

It is a class-file attribute, added in Java 5, that records the generic form of a class, method or field declaration, such as <T:Ljava/lang/Object;>(Ljava/util/List<TT;>;)I. javac reads it when compiling against a library, so that generic library code is type-checked, and reflection exposes it through getGenericType() and friends. The JVM ignores it for linking and execution, which uses only the erased descriptors; that is why generics needed no JVM change.

Q8L3 · Senior EngineerCode

What does this program print?

JAVASignatureQuiz.java
public class SignatureQuiz {
    static <T extends Comparable<T>> T max(List<T> items) {
        return Collections.max(items);
    }
 
    public static void main(String[] args) throws Exception {
        Method m = SignatureQuiz.class.getDeclaredMethod("max", List.class);
        System.out.println(m.getReturnType().getSimpleName());
        System.out.println(m.getGenericReturnType());
        System.out.println(max(List.of("pear", "fig")).length());
    }
}

It prints Comparable, then T, then 4. The return type in the descriptor is the erasure of T, its leftmost bound Comparable, which is also why the method is found with List.class. getGenericReturnType() reads the Signature attribute and reports the type variable T. At the call site javac inserts a cast to String, so length() works: "pear" is the maximum.

Q9L3 · Senior EngineerTricky

Can a class declare void save(List items) and void save(List<Order> items) side by side?

No. The generic method erases to save(List), the same descriptor as the raw one, so the two would be indistinguishable in the class file and javac reports a name clash. This is the flip side of migration compatibility: erasing to the raw descriptor is what lets old callers keep working, and it is also what makes such overloads impossible.

Q10L3 · Senior EngineerScenario

A service still uses a client jar compiled in 2008 with raw types against version 1 of a library. The library team releases version 2 with generic signatures. Will the old jar break?

Not because of the generics. The new signatures, such as List<Order> find(String), erase to the same descriptors as the old raw ones, so the 2008 bytecode still links. Breakage would come from other changes: removed or renamed methods, new bounds that change an erasure, or behaviour changes. Check the release with a binary-compatibility tool, and expect unchecked warnings only when someone recompiles the old client.

Q11L4 · Technical ArchitectDesign

What lessons from the erasure decision would you apply when evolving a widely used internal API?

Decide explicitly which compatibility you must keep: binary (old jars keep linking), source (old code still compiles) and behavioural. Prefer changes that keep the binary contract, as generics kept descriptors, and give consumers a migration path where old and new styles coexist, with warnings rather than errors. Accept a less elegant design if it avoids a flag day, document the limitations it brings, and measure adoption, for example by counting deprecated or unchecked uses, before removing the old path.

Q12L4 · Technical ArchitectTrade-off

Kotlin offers reified type parameters for inline functions. Why does Java not do the same, and what does Java use instead?

Kotlin's reified works only for inline functions: the compiler copies the function body into each call site, where the concrete type is known, so nothing needs to exist at run time. Java does not inline methods at compile time, and its generic methods are compiled once, so there is no place to put the type. Java code passes the type explicitly instead, as a Class<T>, a Supplier<T> or a type token. That is more verbose, but it works for every method, including virtual and library methods, and keeps one compiled body per method.

Q13L5 · Solution ArchitectTrade-off

Your platform must add a capability that the existing API cannot express. Option A is a compatible extension with limitations; option B is a clean new API that every team must migrate to. How do you decide?

Weigh the cost of migration, multiplied by the number of consumers and the risk of stragglers, against the long-term cost of the limitations. Java chose A for generics because the ecosystem was huge and mostly outside its control; C# chose B because its platform was younger and its ecosystem smaller. Option A is usually right when consumers are many and independent, B when they are few, controlled, and the limitations would be paid on every future feature. A hybrid often works: ship the compatible extension now, and design it so that a cleaner API can be layered on later without a second break.

Q14L5 · Solution ArchitectScenario

A team asks whether to wait for Project Valhalla before optimising a service that keeps millions of boxed numbers in generic collections. What do you advise?

Do not wait. Valhalla's value classes are arriving in stages, and fully specialised generics such as an efficient List<int> are further out; neither is part of Java 25. Measure first: if boxing dominates memory or GC time, use primitive arrays, IntStream and the JDK's primitive functional interfaces, or a primitive collections library, behind an interface so the implementation can be swapped later. Revisit when Valhalla features become final in an LTS release, and keep the domain API free of the optimisation.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Erasure implements generics at compile time only.
  • It was chosen for compatibility with pre-generics code and libraries.
  • javac checks, erases, casts and bridges; declarations stay in class-file metadata.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.