我有一个Map<String, Object>
,其中一个值是 List<String>
。目前,我有:
if (!data.containsKey(myVar)) {
List<String> emp = new ArrayList();
data.put(myVar, emp); // myVar is a String
} else {
data.get(myVar).add(otherVar); // "add" gives an error; otherVar is a String
}
我目前的解决方案是这样做
} else {
@SuppressWarnings("unchecked")
List<String> vals = (List<String>) data.get(myVar);
vals.add(otherVar);
data.put(myVar, vals);
}
有更好的解决方案吗?
最佳答案
除非你可以改变Map<String, Object>
至Map<String, List<String>>
,没有更好的解决办法。你需要一个 Actor 阵容。您当然可以添加instanceof
检查并将其提取到辅助方法中,但最终您需要进行强制转换。
有一件事:你不需要做另一件事put
进入 map — vals.add(otherVar)
修改List
它已经在 map 中,它不会返回新的列表实例。
关于单行(强制转换为 List<String>
并在同一行中执行 add
)——这不是很好,因为那时你要么必须容忍“未经检查的强制转换”编译器警告,要么你会必须把@SuppressWarnings("unchecked")
在方法级别,这可以抑制方法内此类的其他警告。
编辑
The Map either has strings or lists as it's values
在这种情况下,您可以考虑将数据结构更改为 Map<String, List<String>>
。由单个元素组成的列表是完全有效的:)
那么代码就变得非常简单了。在 Java 8 中,这是一行代码:
data.computeIfAbsent(myVar, key -> new ArrayList<>()).add(otherVar);
关于java - 如何添加到 HashMap 中的强制列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416940/