I have been into Generics for an hour, I have certain doubts. Lets say I have a class like this :
class Pair<T>
{
public T getFirst() { return first; }
}
Basically my book say this :
Type erasure: The type variables are erased and replaced by their bounding types (or Object for variables without bounds.)
So according to my book statement the code in JVM should look like :
class Pair
{
public Object getFirst() { return first; }
}
Now if I do :
Pair<String> pair = new Pair<>(); //I use Java 7 diamond syntax here.
pair.getFirst()
Is that again my code need to convert from Object
to String
in return type of getFirst
?
Now conisder :
ArrayList<String> files = new ArrayList<>();
The same book say's (with respect to the above code is) :
....the files contain array of Strings.
I'm very much confused about the type erasure rule with the above example of ArrayList
. In this case how come files
array know that it has String
array? (which is contradicting to type erasure rule)
Edit:
In order to see the resulting code of Pair
(that is how type erasure have taken place), how can I use javap
tool here?
Am I missing something here?