简体   繁体   English

HashMap密钥更新与重复输入

[英]HashMap key update vs double entries

I am using a hashmap to store objects with a key that evolves over time. 我正在使用哈希图来存储带有随时间变化的键的对象。

HashMap<String,Stuff> hm = new HashMap<String,Stuff>()
Stuff stuff = new Stuff();
hm.put( "OrignalKey", stuff);

I didn't find anything better than removing "OrignalKey" and put() a new entry with the same object. 我发现没有什么比删除“ OrignalKey”和put()具有相同对象的新条目更好的了。

hm.remove("OriginalKey");
hm.put("NewKey", stuff);

remove() seems to be taking a significant cpu toll hence my questions: remove()似乎占用了大量CPU费用,因此我的问题是:

  1. What is the actual the memory cost to leave duplicate entries (there is no overlapping risk)? 留下重复条目的实际内存成本是多少(不存在重叠风险)?
  2. Am I just missing some neat swapKey() method? 我只是缺少一些简洁的swapKey()方法吗?

What is the actual the memory cost to leave duplicate entries (there is no overlapping risk)? 留下重复条目的实际内存成本是多少(不存在重叠风险)?

Well, you've got an extra entry, and the key itself can't be garbage collected. 好吧,您还有一个额外的条目,而且密钥本身无法进行垃圾回收。 If the key is "large", that could be a problem. 如果密钥为“大”,则可能是一个问题。 It also means that you'll never be able to get an accurate count, you'll never be able to sensibly iterate over all the values, etc. It seems like a bad idea to me. 这也意味着您永远无法获得准确的计数,您永远也无法明智地遍历所有值,等等。对我来说,这似乎是一个坏主意。

Am I just missing some neat swapKey() method? 我只是缺少一些简洁的swapKey()方法吗?

There's no such thing - and it feels like a fairly rare requirement to me. 没有这样的事情-对我来说,这是一个非常罕见的要求。 Any such method would pretty much have to do what you're doing anyway - it has to find the old key, remove it from the data structure, and insert an entry for the new key. 任何这样的方法几乎都必须做您正在做的事情-它必须找到旧密钥,将其从数据结构中删除,然后为新密钥插入一个条目。 I can't easily imagine any optimizations possible just by knowing about both operations at once. 我不能轻易想象一下一次知道两个操作就可能实现的优化。

swapping of the key is not easily possible, since the key is used for hashing. 密钥的交换不容易实现,因为密钥用于散列。 changing the key means that the hashvalue is most probably different, too. 更改键意味着哈希值也很可能也不同。 in this case, changing the key conforms to deletion and following reinsertion 在这种情况下,更改密钥即表示删除,然后重新插入

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

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