【问题标题】:how to fix a static generic method that recives an array of objects如何修复接收对象数组的静态泛型方法
【发布时间】:2019-03-26 09:50:14
【问题描述】:

我有一个关于我编写的静态函数的问题,该函数接收包含键和值的通用对象数组。当它找到具有相同值的键时,它会添加该键的值;但是,我在将函数设为静态时遇到了问题。代码如下:

public static<K,V extends Number> void mapSumOfValues(/*Map<K,V> h,*/ DataObject<K, V> []dataarray) {
    Map<K,V> h = new HashMap<>();
    Integer sum = 0;
    for(DataObject<K,V> d: dataarray) {
        h.merge(d.getKey(), d.getValue().intValue(), Integer:: sum);
    }

我得到错误:

方法merge(K, V, BiFunction)在 Map 类型不适用于参数 (K, int, 整数::总和)

【问题讨论】:

  • 嗨,使用 V extends Integer 或 h.merge(d.getKey(),new Integer(d.getValue().intValue()), Integer:: sum);

标签: java generics static hashmap


【解决方案1】:

您的合并功能仅适用于Integer,因此您需要一个Map&lt;K, Integer&gt;。

Map<K, Integer> h = new HashMap<>();
for (DataObject<K, V> d : dataarray) {
    h.merge(d.getKey(), d.getValue().intValue(), Integer::sum);
}

【讨论】:

  • 您确定 Integer::sum 会自动装箱到 BiFunction&lt;Integer, Integer&gt; 中吗?不是说不会,但我认为这可能有问题。
  • 我检查过,事实上确实如此!所以不要介意我上面的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 2012-12-04
  • 2010-10-16
  • 2012-08-26
  • 2012-02-27
  • 2012-02-10
相关资源
最近更新 更多