0

Here is my problem: my function in class A:

public void setData(Map<String,? extends ArrayList<? extends SomeInterface>>){...}

my call:

Map<String, ArrayList<ImplementsSomeInterface>> a=...;
instanceOfA.setData(a); //does not compile
instanceOfA.setData((Map<String,? extends ArrayList<? extends SomeInterface>>) a); // works thanks to the Casting.

I don't think this is clean. Is there a way to avoid the casting without droping the wildcard use in the function?

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
giscope
  • 77
  • 1
  • 8

2 Answers2

3

First your setData method should read:

public void setData(Map<String,? extends List<? extends SomeInterface>>)

Your map declaration should read:

Map<String, List<ImplementsSomeInterface>> a = ...;

Which is pretty much what you've got following your edits to the original question. The change I've made from ArrayList to List doesn't effect the behaviour of the code.

Following comments:

public static void main() 
{
    Map<String, List<Double>> map = new HashMap<String, List<Double>>();
    map.put("prices", new ArrayList<Double>(Arrays.asList(1.1, 2.2, 3.3)));

    setData(map);
}

public static void setData(Map<String,? extends List<? extends Serializable>> map)      
{
}
Nick Holt
  • 33,455
  • 4
  • 52
  • 58
  • assuming I use `public void setData(Map>)` I still have to cast the parameter in the call as follow `instanceOfA.setData((Map>) a);` is there a way to avoid the casting? – giscope Apr 26 '12 at 13:52
  • Not in the version of Java 1.6 I'm using, I tried it :-) I'll add the code to my answer. – Nick Holt Apr 26 '12 at 14:06
1

The problem is that setData takes as an argument a Map<String,? extends ArrayList<? extends SomeClass>>Map> whereas in your first call(the one that doesn't compile) you are trying to pass it a Map<String,? extends SomeClass>

Java cannot automatically cast a subclass of SomeClass to a subclass of ArrayList<? extends SomeClass> because it is not neccesarily an instance of ArrayList.

Marcus Mathioudakis
  • 837
  • 1
  • 6
  • 19