即使方法使用更多泛型类型,方法调用也不匹配方法签名 [英] Method call doesn't match method signature even though method is using more generic types

查看:111
本文介绍了即使方法使用更多泛型类型,方法调用也不匹配方法签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法:

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 );
}

调用该方法:

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

错误(重新格式化):

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:

  • 地图是地图
  • 字符串是一个对象(x2)
  • 长是数字

我对此有些困惑.

推荐答案

是后面的两个.字符串和对象不是同一类型.泛型不是协变的,它们是不变的.类型必须完全匹配.与Long和Number相同.

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

可以通过以下方式致电

 HashMap<String, Integer> myMap = new HashMap<>();
 incrementMapCounter( myMap, "warble" );

这篇关于即使方法使用更多泛型类型,方法调用也不匹配方法签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆