0

I'm trying to use a wildcard type in a method signature and pass different parameterized types. It works fine if it's only a GenericItemWrapper, but it fails if that GenericItemWrapper is a type parameter itself. Here's what eclipse complains about:

The method DoStuff(Map<String, Test.GenericItemWrapper<?>>) in the type Test 
is not applicable for the arguments (Map<String, Test.GenericItemWrapper<String>>)

Here's the code:

import java.util.Map;

public class Test
{

  public static void main(String[] args)
  {
    Map<String, GenericItemWrapper<Long>> longWrapper = null;
    Map<String, GenericItemWrapper<String>> stringWrapper = null;

    Test t = new Test();
    t.DoStuff(longWrapper); // error here
    t.DoStuff(stringWrapper); // error here
  }

  public void DoStuff(Map<String, GenericItemWrapper<?>> aParam)
  {
    ;
  }

  public static class GenericItemWrapper<ItemType>
  {
    private ItemType mItem;

    public GenericItemWrapper(ItemType aItem)
    {
      mItem = aItem;
    }

  }
}
Buffalo
  • 3,861
  • 8
  • 44
  • 69

2 Answers2

2

Try this:

public void DoStuff(Map<String, ? extends GenericItemWrapper<?>> aParam) {}

you can refer to this answer for more investigation about generics: Java nested generic type

Basically the first ? refers to the fact that you are creating a generic like Map<String, ?> and so you can put int the map any kind of Object.

The second ?, the one inside the GenericItemWrapper<?> simply generalizes the item as you probably know.

So writing Map<String, ? extends GenericItemWrapper<?>> means that you are generalizing the Map value (using the first ?) and that the type of generic object that you want to put inside the map has to be a generalized type too (aka extends GenericItemWrapper<?>)

Tonio Gela
  • 85
  • 8
0

Eclipse does not complain about:

public <T> void DoStuff(Map<String, GenericItemWrapper<T>> aParam) {
    ;
}
Ralf Renz
  • 1,061
  • 5
  • 7