2

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?

4

2 回答 2

4

Your confusion comes from what the compiler does and what the JVM does.

Pair<String> pair = new Pair<>(); //I use Java 7 diamond syntax here.
String first = pair.getFirst();

is equivalent in the JVM to

Pair pair = new Pair(); 
String first = (String) pair.getFirst();

In the case of Map.get()

Map<Key, Value> map = ...
Value value = map.get(key);

is in the JVM

Map map = ...
Value value = (Value) map.get(key);

Is that again my code need to convert from Object to String in return type of getFirst?

No conversion occurs. The object is not altered. All that happens is there might be a cast check of the reference.

In order to see the resulting code of Pair(that is how type erasure have taken place), how can I use javap tool here?

Use javap -c -classpath . ClassUsingPair

于 2012-08-08T11:28:53.937 回答
0

1. Erasure is a process in which Compiler removes the Type parameter and Type arguments from during the compilation from Class and Method, Variables etc...

2. Box becomes Box, this is called raw-type, Raw-type is one where the generic class or interface name will be without type argument.

3. So during run-time one won't find the Generics...its mainly done to make the code that didn't used generics to run without any problem, mainly those that were written before Generics came into existence.

4. Generic Class won't be instantiated, cause it needs its constructor to be initiated, and that wont happen as the original Type parameter wont be there during the Runtime.

于 2012-08-08T11:26:11.760 回答