R.L
R.L

Reputation: 109

how does java handle using genericity and polymorphism with rawtype list

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

Answers (1)

Andy Turner
Andy Turner

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 Objects that aren't Lists, but no Lists that aren't Objects.

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

Related Questions