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
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)andadd(Object)(the parameter types are raw becausethingis raw-typed).If you pass a raw-typed
List, that matchesadd(List)andadd(Object).add(List)is more specific thanadd(Object), because there areObjects that aren'tLists, but noLists that aren'tObjects.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.