我遇到一个问题,当我想要更改嵌套 HashMap 中的值时,其他 HashMap 会被覆盖。
例如,我有一个键名称 Alligator,它存储一个包含键 Weight 和 Size 的 HashMap。我希望能够更改与尺寸相关的值,但根本不影响重量。在 yml 文件中,这就是它的样子。
Alligator:
Weight: 100.0
Size: 10.0
这就是我希望发生的事情。
Alligator:
Weight: 150.0
Size: 10.0
这是我之前发现的一些代码,可以让我更改值,但可以覆盖...
HashMap< String, HashMap< String, Double>> data = new HashMap<>();
data.put("Alligator", new HashMap() {
{
put("Size", 10.0
}
});
HashMap< String, HashMap< String, Double>> data = new HashMap<>();
data.put("Alligator", new HashMap() {
{
put("Weight", 100.0
}
});
最佳答案
data.put("Alligator", new HashMap() {
{
put("Weight", 100.0);
}
});
如果“Alligator”键已存在于外部映射中,则将覆盖其内部映射。
您必须首先检查是否存在:
Map<String, Double> inner = data.get("Alligator");
if (inner != null) {
inner.put("Weight", 100.0);
} else {
data.put ("Alligator", new HashMap() {
{
put("Weight", 100.0);
}
});
}
顺便说一句,我不会为内部 Map 使用 HashMap
实例的匿名子类。
您可以用这个更简单的代码替换它:
Map<String, Double> inner = data.get("Alligator");
if (inner == null) {
inner = new HashMap<>();
data.put ("Alligator",inner);
}
inner.put("Weight", 100.0);
关于java - 嵌套 Hashmap 覆盖其他键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30907778/