Reputation: 109
i was exploring lists and genericity when i found the following problem
if we have this object (which compile with any error or warning):
class Thing<TYPE>{
void add(List<TYPE> ls){...}
void add(TYPE ls){...}
}
then we do:
Thing<List> thing = new Thing<List>(); //warn about rawtypes but compile
List list=new ArrayList(); //same thing here
thing.add(list); //warn about unsafe cast but compile
how does java decide which method to call?
i understand this is probably something to avoid at all cost for multiple reasons but since it still compile (at least eclipse said it can) im still curious of how it would behave
Upvotes: 0
Views: 84
Reputation: 140484
Java chooses the most specific method overload.
In this case, you're calling a method named add
, so the compiler has two choices: add(List)
and add(Object)
(the parameter types are raw because thing
is raw-typed).
If you pass a raw-typed List
, that matches add(List)
and add(Object)
. add(List)
is more specific than add(Object)
, because there are Object
s that aren't List
s, but no List
s that aren't Object
s.
So, it chooses add(List)
.
However, the more important thing to appreciate here is that you shouldn't use raw types if at all possible.
Upvotes: 1