LSDeva
LSDeva

Reputation: 441

Method overloading with collection types doesn't work as expected

Consider the following class with overloaded methods.

public final class TeaParty {
  private void travellerListed( Collection o) { 
    System.out.println("travellerListed(Collection<?>)"); 
  } 
  private void travellerListed( List s) { 
    System.out.println("travellerListed(List<Number>)"); 
  } 
  private void travellerListed( ArrayList i) { 
    System.out.println("travellerListed(ArrayList<Integer>)"); 
  }

  private void method(List t) { 
    travellerListed(t) ; 
  }

   public static void main(String[] args) { 
      TeaParty test = new TeaParty(); 
      test.method(new ArrayList ()); 
  } 
}

I'm expecting "travellerListed(ArrayList)" as output. But I get "travellerListed(Collection)". What cause for this unexpected overloading ?

Upvotes: 0

Views: 235

Answers (1)

Eran
Eran

Reputation: 393966

Actually the code you posted results in "travellerListed(List<Number>)", since you are passing the ArrayList to method, whose argument type is a List, so for the call to travellerListed the compiler chooses private void travellerListed( List s), since method overloading resolution is determined by the compile-time type of the arguments (which means private void travellerListed( ArrayList i) cannot be chosen), and a List is a more specific type than a Collection (which explains why private void travellerListed( Collection o) is not chosen).

Upvotes: 3

Related Questions