0

The method:

public static void incrementMapCounter( Map<Object,Number> tabulationMap, Object key ) {
  Number value = 0;
  if ( tabulationMap.containsKey(key) ) {
    value = tabulationMap.get(key);
  }
  value = value.doubleValue() + new Double(1);
  tabulationMap.put( key, value );
}

Call to the method:

Map<String,Long> counts = new HashMap<>();
String key = "foo-bar";
incrementMapCounter( counts, key );

Error (reformatted):

The method
    incrementMapCounter(Map<Object,Number>, Object)
in ... is not applicable
    for the arguments  (Map<String,Long>, String)

The method signature is either a matching type or more generic:

  • Map is a Map
  • String is an Object (x2)
  • Long is a Number

I'm a bit confused on this one.

Mark Bennett
  • 1,446
  • 2
  • 19
  • 37

2 Answers2

1

It's the later two. String and Object are not the same type. Generics are not covariant, they are invariant. The types have to match exactly. Same with Long and Number.

For your method signature you might try:

public static <T> void incrementMapCounter( Map<? extends T, ? extends Number> map, T key )
{ ...

Which can be called by:

 HashMap<String, Integer> myMap = new HashMap<>();
 incrementMapCounter( myMap, "warble" );
markspace
  • 10,621
  • 3
  • 25
  • 39
  • How would you declare it if using both arguments, map and key? I've tried a couple ways, void incrementMapCounter( Map,? extends Number> map, Object key) // void incrementMapCounter( Map,? extends Number> map, extends Object> key ) // void incrementMapCounter( Map map, K key ). In the flagged "duplicate of" question, in the last paragraph of @Yishai's answer http://stackoverflow.com/a/2745357/295802, it seems to indicate that this is impossible: "the only way to do both at the same time is to have a specific type" – Mark Bennett Oct 24 '14 at 17:15
  • Hah! Sorry missed the 2nd argument. Use a generic method to do that. I'll update my answer. – markspace Oct 24 '14 at 19:48
0

Generics are invariant so the arguments will need to match the arguments passed in so that values can be added to the Collection

public static void incrementMapCounter(Map<String, Long> map, Object key) {
Reimeus
  • 158,255
  • 15
  • 216
  • 276