简体   繁体   English

为什么在哈希映射中存储哈希映射时填充多个哈希映射而不是 1?

[英]Why are multiple hashmaps being populated instead of 1 when storing hashmaps inside of a hashmaps?

I'm using the spigot api in Java to create a plugin (for minecraft) and to make cooldowns I've stored hashmaps inside of a hashmap.我正在使用 Java 中的插口 api 创建一个插件(用于我的世界)并进行冷却,我已将哈希图存储在 hashmap 中。 The outer hashmap is:外层 hashmap 为:

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

When I try to add to a certain map inside the outer map (the problem isn't the cdId, I've checked):当我尝试在外部 map 内添加某个 map 时(问题不是 cdId,我已经检查过):

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

It adds it to the correct map (with the key totem_of_storms_1) and also to another map (with the key totem_of_storms_2).它将它添加到正确的 map(使用密钥 totem_of_storms_1)以及另一个 map(使用密钥 totem_of_storms_2)。

Another example of when this happens is if cdId is totem_of_time_2 it will add to totem_of_time_1 as well.发生这种情况的另一个示例是,如果 cdId 为 totem_of_time_2,它也会添加到 totem_of_time_1。

I have checked that it is this line that is adding to multiple hashmaps itemCooldowns.get(cdId).put(p.getUniqueId(), System.currentTimeMillis() + cdTime);我检查过是这条线添加到多个哈希itemCooldowns.get(cdId).put(p.getUniqueId(), System.currentTimeMillis() + cdTime); but I have no idea why但我不知道为什么

When you have an object referenced in multiple place, modifying it from one access point will make it visible from any other access point.当您在多个位置引用 object 时,从一个访问点对其进行修改将使其在任何其他访问点都可见。


A very simple example can be done with a List一个非常简单的例子可以用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]

Your case is a bit more complex with stays the same (I replaced UUID by String for visibility)你的情况有点复杂,保持不变(为了可见性,我用String替换了UUID

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM