我正在尝试编写一个通用函数,该函数将元素添加到Map的Collection中。这适用于Map的List:
public static void addToMapOfLists(Map> map, TKey key, TVal val) {
List list = map.get(key);
if (list == null) {
list = new ArrayList<>();
list.add(val);
map.put(key, list);
} else
list.add(val);
}
我想使此功能在Map>以及Map>上均可使用。我希望这应该可行,因为这两个实现都具有我调用的Collection成员的add(TVal)。
我的问题是,当我尝试将参数Map> map更改为Map> map时,我需要以某种方式用对new ArrayList<>();的实现者的构造函数的调用来替换Collection。
参考方案
您将必须向方法传递一个附加参数-Supplier个实例的一个Collection。
这是一种可能的实现:
public static > void addToMapOfCollections(Map> map, TKey key, TVal val, Supplier supplier)
{
Collection col = map.get(key);
if (col == null) {
col = supplier.get ();
col.add(val);
map.put(key, col);
} else {
col.add(val);
}
}
这是另一个选择:
public static void addToMapOfCollections(Map> map, TKey key, TVal val, Supplier> supplier)
{
Collection col = map.get(key);
if (col == null) {
col = supplier.get ();
col.add(val);
map.put(key, col);
} else {
col.add(val);
}
}
并且使用更少的代码(如Gerald所建议):
public static void addToMapOfCollections(Map> map, TKey key, TVal val, Supplier> supplier)
{
map.putIfAbsent(key, supplier.get());
map.get(key).add(val);
}
我测试了第二个变种:
Map> map = new HashMap>();
addToMapOfCollections(map,"String1",5,HashSet::new);
addToMapOfCollections(map,"String2",67,ArrayList::new);
addToMapOfCollections(map,"String2",68,ArrayList::new);
System.out.println (map);
for (Collection col : map.values ()) {
System.out.println (col.getClass () + " : " + col);
}
输出:
{String2=[67, 68], String1=[5]}
class java.util.ArrayList : [67, 68]
class java.util.HashSet : [5]
无法从ArrayList 转换为List - java
当我写下面的代码时,编译器说 无法从ArrayList转换为Listprivate List get(){ return new ArrayList(); } 但是当我用通配符编写返回类型时,代码会编译。private List&l…合并List 和List > - java
鉴于: List integers = new ArrayList<>(Arrays.asList( 10, 12 )); List> optionalIntegers = Arrays.asList( Optional.of(5), Optional.em…实例化类型的泛型类 - java
我正在为SCJP / OCPJP学习,并且遇到了一个对我来说很奇怪的示例问题。该示例代码实例化了两个通用集合:List> list = new ArrayList>(); List extends Object> list2 = new ArrayList extends Object>(); …List 是List 的子类吗?为什么Java泛型不是隐式多态的? - java
我对Java泛型如何处理继承/多态感到困惑。假设以下层次结构-动物(父母)狗-猫(儿童)因此,假设我有一个方法doSomething(List animals)。根据继承和多态性的所有规则,我假设List是List,而List是List? - java
假设我有以下课程:class A { int id; List b; } class B { int id; } 我想在A.id到B.id的列表之间创建一个映射(Map>,其中key = A.id,而List对应于每个A的B.id字段的列表)…