Search code examples
javagenericstype-erasure

Java Generics - Erasures Mechanism


Say.., the Java compiler erases all type info, and replaces all occurrences of those with their upper bounds (if mentioned) or Object..

My questions is: no insertion of casts takes place here. Casting occurs later when some other class is compiled against this type info-free class, where, depending on the type argument(s) that other class supplements, the generic class is recompiled (for a second time) and all casts are put in place and the class is ready for run time.., right?


Solution

  • No, the class is not recompiled. The casts happen on the boundary between concrete and generic types.

    If you're trying to figure it out, you could look at using a generic class as a raw type (i.e. without the generics). For instance ArrayList:

    List l = new ArrayList(); // An `ArrayList<String>` before generics.
    
    l.add("Hello");
    String s = (String) l.get(0);
    

    The casts are inserted where the concrete type is known (String in this case). They are not inserted inside the ArrayList class, and there isn't really a need for that.