Reputation: 27445
Consider the following code:
List<Integer>ints= new ArrayList<Integer>();
lst.add(new Object());//no suitable method found for add(Object)...
Why this error is causing? On a compile time we have type erasure, and method boolean add (E e)
after erasure will have signature add(Object o)
. Can you write in detail how ompiler work in this case?
And what about bridge method? As i understood bridge metod have the following implements:
boolean add(Object o){return this.add((Integer) o)}
Upvotes: 1
Views: 344
Reputation: 136102
Bridge methods go in class definition, not in methods, example:
public class Test implements Comparable<Test> {
public int compareTo(Test o) {
return ...;
}
...
compiler will add a bridge method (invisible) here
public int compareTo(Object o) {
return compareTo((Test)o);
}
because Comparable interface in bytecode has int compareTo(Object o)
method and for JVM to detect that the class implements this method the class needs int compareTo(Object o)
Upvotes: 1
Reputation: 280167
You aren't evaluating
lst.add(new Object());
at runtime, you are evaluating it at compile time. At compile time, there is no method List<Integer>#add(Object)
.
Upvotes: 1
Reputation: 272687
Type erasure occurs after the compiler has perform type-checking. If it were the other way around, there would be no point in generics!
Upvotes: 7