How does the java compiler know to provide appropriate cast to the objects in a generic collection when the type information isn't available at runtime due to erasure?
Asked
Active
Viewed 1,096 times
2 Answers
1
Whenever you call e.g. list.get(foo)
, and the list is an ArrayList<String>
, then the result of get
is casted to a String
by the caller, not the callee. The caller knows at compile time what the result should be cast to (a String
), so the cast can be inserted there.

Louis Wasserman
- 191,574
- 25
- 345
- 413
0
As per oracle tutorial
- Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
- Insert type casts if necessary to preserve type safety.
- Generate bridge methods to preserve polymorphism in extended generic types.
So, your class file contains either bounded class (or) Object instead of generic type.

kosa
- 65,990
- 13
- 130
- 167
-
But List
list = new ArrayList – Phoenix Oct 23 '12 at 15:53this will be replaced by List list = new ArrayList(); so how does the compiler know while retrieving an object from the list that the object type needs to be cast into string ? -
see this thread that may clear your confusion. At byte code level .class file stores some generic information which can be manipulated using relections. http://stackoverflow.com/questions/937933/where-are-generic-types-stored-in-java-class-files – kosa Oct 23 '12 at 15:55