【问题标题】:Why are multiple hashmaps being populated instead of 1 when storing hashmaps inside of a hashmaps?为什么在哈希映射中存储哈希映射时填充多个哈希映射而不是 1?
【发布时间】:2020-06-22 12:21:49
【问题描述】:

我正在使用 Java 中的 spigot api 来创建一个插件(用于我的世界)并进行冷却,我将哈希图存储在哈希图中。 外层hashmap是:

Map<String, Map<UUID, Long>> itemCooldowns = new HashMap<>();

当我尝试添加到外部地图内的某个地图时(问题不在于 cdId,我已经检查过):

itemCooldowns.get(cdId).put(p.getUniqueId(), System.currentTimeMillis() + cdTime);

它将它添加到正确的地图(使用 key totem_of_storms_1)和另一个地图(使用 key totem_of_storms_2)。

发生这种情况的另一个例子是,如果 cdId 是 totem_of_time_2,它也会添加到 totem_of_time_1。

我检查过是这条线添加到多个哈希映射itemCooldowns.get(cdId).put(p.getUniqueId(), System.currentTimeMillis() + cdTime);,但我不知道为什么

【问题讨论】:

  • 这意味着你的外部 Map 的多个键与同一个 Map&lt;UUID, Long&gt; 实例相关联。
  • 好的,谢谢,我会调查一下
  • 尝试发布minimal, reproducible example。很可能相同的内部映射作为外部映射中多个键的值存在。
  • Eran 和 gscaparrotti 感谢您的帮助,您是对的。如果您愿意,请发布答案并将其设置为正确。
  • @scruffyboy13 如果他们不写答案,请知道在 Stack Overflow 上欢迎并鼓励您写下并接受自己对自己问题的答案。

标签: java hashmap


【解决方案1】:

当您在多个位置引用了一个对象时,从一个访问点对其进行修改将使其在任何其他访问点都可见。


一个非常简单的例子可以用List来完成

List<Integer> a = Arrays.asList(1, 2, 3, 4);
List<Integer> b = a;

System.out.println(b); // [1, 2, 3, 4]
a.set(1, 123);
System.out.println(b); // [1, 123, 3, 4]

您的情况有点复杂,但保持不变(我将 UUID 替换为 String 以提高可见性)

Map<String, Map<String, Long>> items = new HashMap<>();

Map<String, Long> m1 = new HashMap<>(Map.of("a", 123L));
itemCooldowns.put("a", m1);

Map<String, Long> m2 = new HashMap<>(Map.of("b", 456L)); // put m2 on 2 different keys
items.put("b", m2);
items.put("c", m2);

System.out.println(itemCooldowns); // {a={a=123}, b={b=456}, c={b=456}}

items.get("c").put("123", 789L);
System.out.println(items);         //{a={a=123}, b={b=456, 123=789}, c={b=456, 123=789}}

/* Modifying from access point 'c' make it also accessible from access point 'b'
items -> a=m1
      -> b=m2
      -> c=m2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多