问题
在呈现的代码中,我们声明:
HashMap<Integer, String> map = new HashMap<>();
和
public static <K,V> Map<K,V> fillMap(Map<K,V> map, K[] keys, V[] values)
因此,如果我们调用
map = MyUtil.fillMap(map, keys, values);
我们尝试将Map<...>(由MyUtil::fillMap 返回)分配给HashMap<...>。这不起作用,因为 Map 不是 HashMap。
可能的解决方案
我想到了两种方法来解决这个问题:
- 要么改变
map的类型,
- 或将
MyUtil::fillMap 的返回类型设为通用。
1。更改map的类型:
我们可以将map的类型从HashMap<...>改为Map<...>:
Map<Integer, String> map = new HashMap<>();
...
map = MyUtil.fillMap(map, keys, values);
Ideone demo
2。将MyUtil::fillMap 的返回类型设为泛型:
通过添加一个额外的泛型参数,我们可以使返回类型的具体实现也泛型:
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
final Integer[] keys = IntStream.range(0, 12).boxed().toArray(Integer[]::new);
final String[] values = new String[] {"Jan", "Feb", "Mar", "Apr", "Mai", "Jun",
"Jul", "Aug", "Sep", "Okt", "Nov", "Dez"};
map = MyUtil.fillMap(map, keys, values);
System.out.println(map);
}
public static <K, V, M extends Map<K, V>> M fillMap(M map, K[] keys, V[] values) {
final int l = keys.length;
for (int i = 0; i < l; i++) {
map.put(keys[i], values[i]);
}
return map;
}
Ideone demo
奖励:返回值的无状态构造
如果不需要将使用的映射的具体实现传递给方法,我会提出第三个选项,创建映射以在方法内返回:
public static <K, V> Map<K, V> fillMap(K[] keys, V[] values) {
return IntStream.range(0, keys.length)
.boxed()
.collect(Collectors.toMap(
index -> keys[index],
index -> values[index]));
}
Ideone demo