Method call doesn't match method signature even though method is using more generic types [duplicate]

喜欢而已 提交于 2019-12-13 05:25:37

问题


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.


回答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" );



回答2:


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) {


来源:https://stackoverflow.com/questions/26551403/method-call-doesnt-match-method-signature-even-though-method-is-using-more-gene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!