简体   繁体   中英

What is the type erasure of “?”?

If I have the following method:

public <U extends Number> void doSomething(List<U> l){      
}  

Then due to type erasure the compiler will make it to doSomething(List<Number> l) . Right?
If this is the case, then why it is not possible to declare the following along with this:

public void doSomething(List<?> l){  
}

Isn't this second method, type erased to doSomething(List<Object> l) ? Why do I get compiler error of same erasure for these 2 methods?

Your thinking is wrong. Erasure leads to both methods having this signature ( List argument types being erased):

public void doSomething(List l) {  
}

Hence, the collision. What you thought was possible to do is this:

public <U extends Number> void doSomething(U argument) {      
}  
public <U extends Object> void doSomething(U argument) {      
}

In this case, after erasure, the method signatures will become this (after U having been erased)

public void doSomething(Number argument) {      
}  
public void doSomething(Object argument) {      
}  

In this case, there is no signature collision.

? is used as wildcard in generics.

It will be erased.

U extends Number tells that upper bound is Number

List<?> doesn't tell what is upper bound.

EDIT: Based on edited question, after compilation, byte code just contains.

public void doSomething(List argument) {      
}  
public void doSomething(List argument) {      
}  

Inheritance in generics is little different than what we know as inheritance in java.

1. ? is used as wild card in Generics.

Eg:

Assume Animal is a Class .

ArrayList<? extends Animal> ArrayList<? extends Animal> means Any Class's instance which extends Animal

During the Erasure , which is a process in which Compiler removes the Generics in Class and Methods during the Compilation time , to make the Generics code compatible to the one which was written when Generics were not introduced.

So ? and U will be removed during compilation time.. so during runtime it will be absent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM