-1

In a library project, I have :

public interface InterfaceA {
}

public interface InterfaceB {
}

public void myMethod(Map<? extends InterfaceA, List<? extends InterfaceB>> map) {
//do something
}

Then I have another project (having this library as a dependency) that contains two object implementing these interfaces :

public class ObjectA implements InterfaceA {
}

public class ObjectB implements InterfaceB {
}

When I try to call the library method myMethod like this :

HashMap<ObjectA, List<ObjectB>> hashMap = new HashMap<>();
//populate hashmap
myMethod(hashMap);

I get a compilation warning saying there is an argument mismatch.

What am I missing here ? Does it have something to do with the map ?

EDIT : The exact error (it's not a warning actually) is :

incompatible types: HashMap<ObjectA,List<ObjectB>> cannot be     converted to Map<? extends InterfaceA,List<? extends InterfaceB>>
nios
  • 1,153
  • 1
  • 9
  • 20

3 Answers3

3

Generics are invariant.

If your method declares:

Map<? extends InterfaceA, List<? extends InterfaceB>>

Then the second type parameter has to be exactly List<? extends InterfaceB>.

You can fix it by using:

Map<? extends InterfaceA, ? extends List<? extends InterfaceB>>

Instead.

Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
  • Thanks! That did the trick, even if I don't clearly understand the syntax here. I clearly have to read a bit more about generics. – nios Aug 30 '16 at 13:11
1

You either modify your Hashmap creation for this:

Map<? extends InterfaceA, List<? extends InterfaceB>> hashMap = new HashMap<>();

or modify your method definition for this:

public <A extends InterfaceA, B extends InterfaceB> void myMethod(Map<A, List<B>> map) {
    //do something
  }
jalv1039
  • 1,663
  • 3
  • 17
  • 21
0

Declare your map as

HashMap<ObjectA, List<? extends InterfaceB>> hashMap = new HashMap<ObjectA, List<? extends InterfaceB>>();
talex
  • 17,973
  • 3
  • 29
  • 66