Reputation: 54074
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?
Upvotes: 1
Views: 135
Reputation: 220842
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.
Upvotes: 8
Reputation: 66637
?
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.
Upvotes: 2
Reputation: 33534
1. ?
is used as wild card in Generics.
Eg:
Assume Animal is a Class.
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
Upvotes: 1