1

For the below Class Structure:

class BaseClass{}
   class A extends BaseClass{}
   class B extends BaseClass{}

I have this method in main:

public static void goThroughMap(Map<String,Collection<? extends BaseClass>> myMap) {}

Now to call this method , i am doing something like:

Map<String,Collection<B>> myMap = new HashMap<>();
goThroughMap(myMap); // is causing a compile time error

The error is:

The method goThroughMap(Map<String,Collection<? extends BaseClass>>)  is not applicable for the arguments (Map<String,Collection<B>>)

So, how should i modify my method parameters to make this work? Any pointers for further reading are welcome.

I have seen related questions by other users(see links below), but none of them seem solve the issue here:

  1. PECS in generics
  2. Upper and Lower Bound Question
Community
  • 1
  • 1
bartender
  • 25
  • 2
  • 4

2 Answers2

0

You have to generify your method properly:

public static <T extends BaseClass> void goThroughMap(Map<String, Collection<T>> myMap) {
  ...
}
Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
  • Can you point out what exactly is wrong with my declarations. Both your and Scrooge McD's answers work for me. – bartender Sep 02 '14 at 10:26
0

You can use the following declaration for your method :

public static void goThroughMap(Map<String,? extends Collection<? extends BaseClass>> myMap)

You can refer to this link for more details on such types : Generics FAQ

Scrooge McD
  • 335
  • 1
  • 3
  • 12