9

I have a problem with bounded nested wildcards in Java generics.

Here's a common case:

public void doSomething(Set<? extends Number> set) {}

public void callDoSomething() {
    Set<Integer> set = new HashSet<Integer>();
    doSomething(set);
}

This is standard Java generics, works fine.

However if the wildcard becomes nested, it no longer works:

public void doSomething(Map<String, Set<? extends Number>> map) {}

public void callDoSomething() {
    Map<String, Set<Integer>> map = new HashMap<String, Set<Integer>>();
    doSomething(map);
}

This leads to a compiler error.

I've tried a variety of casts and wildcard permutations, but I'm unable to get this working. I don't recall seeing this issue before, and I've worked with generics for years. Am I just too tired and missing something obvious?

Pang
  • 9,564
  • 146
  • 81
  • 122
nilskp
  • 3,097
  • 1
  • 30
  • 34
  • 2
    There's an explanation for this in the Java Generics FAQ: http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ104 – Rag Dec 11 '14 at 23:27

3 Answers3

15

So the problem is, doSomething could be implemented as:

public void doSomething(Map<String, Set<? extends Number>> map) {
    Set<Float> set = ...;
    map.put("xyz", set);
}

You need to decide what you actually mean.

Probably something like:

public void doSomething(Map<String, ? extends Set<? extends Number>> map) {}
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • Yes, I just independently realized this. I could have sworn I tried that yesterday, but I probably had some other subtle change. – nilskp Aug 04 '10 at 13:34
1

this will work for you:

public void doSomething(Map<String, ? extends Set<? extends Number>> map) {}
newacct
  • 119,665
  • 29
  • 163
  • 224
0

To make code to work Create HashMap as:

Map<String, Set<? extents Number>> map = new HashMap<String, Set<? extents Number>>();
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
YoK
  • 14,329
  • 4
  • 49
  • 67