方法:
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)
方法签名是匹配类型或更通用的:
- map 就是 map
- 字符串是一个对象 (x2)
- 长是一个数字
我对这个有点困惑。
最佳答案
是后两个。 String 和 Object 不是同一类型。泛型不是协变的,它们是不变的。类型必须完全匹配。与长整型和数字相同。
对于您的方法签名,您可以尝试:
public static <T> void incrementMapCounter( Map<? extends T, ? extends Number> map, T key )
{ ...
可以通过以下方式调用:
HashMap<String, Integer> myMap = new HashMap<>();
incrementMapCounter( myMap, "warble" );
关于java - 即使方法使用更通用的类型,方法调用也不匹配方法签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26551403/