简体   繁体   English

从哈希图提取元素并更新它

[英]extract an element from an hash map and update it

If I extract an element from a hash map through the method get(<key>) and update the extracted element, will these updates persist in the map? 如果我通过get(<key>)方法从哈希映射中提取元素并更新提取的元素,这些更新是否会保留在映射中? Or do I have to re-insert the element back to the hash map? 还是我必须将元素重新插入到哈希图中?

If you change fields of the object you got out, like this... 如果您更改离开对象的字段,就像这样...

Thing thing = map.get(key);
thing.setOtherThing(yetAnotherThing);

then that'll update the value in the map. 然后将更新地图中的值。

On the other hand, if you modify the reference that you obtained by getting a value out of the map... 另一方面,如果您修改通过从地图中获取值获得的参考...

Thing thing = map.get(key);
thing = doSomethingWith(thing);

then you need to put it back into the map. 那么您需要将其放回地图中。

If you modify the object obtained by the Map.get(K) method, the object does not need to be re-inserted. 如果修改通过Map.get(K)方法获得的对象,则无需重新插入该对象。 However, if you change a key in a way that the hashCode() function is affected, then you need to remove the map entry before modifying the key and then you can put back your value using your new key. 但是,如果以影响hashCode()函数的方式更改键,则需要在修改键之前删除映射条目,然后才能使用新键放回值。

Consider the following map corruption case: 考虑以下地图损坏情况:

Map<List<String>, String> map = new HashMap<List<String>, String>();

List<String> key1 = new ArrayList<String>();
key1.add("key1");

map.put(key1, "value1");
System.out.println(map.get(key1)); //prints "value1"

key1.add("buzz2");
System.out.println(map.get(key1)); //prints "null"

List<String> k = map.keySet().iterator().next();
System.out.println(map.get(k)); //prints "null"

Morale of the story: for maps, always use immutable keys like String or int. 故事的士气:对于地图,请始终使用不可变的键,例如String或int。

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

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