简体   繁体   中英

Returning a Object in a Hashset in Java

Hi I have a HashSet like the following in a class called Memory:

Set<Idea> ideas = new HashSet<Idea>();

The generic type "Idea" is another class I wrote that has hashcode() and equals() overriden. I want to be able to get(and not remove) an Idea object in the HashSet ideas, then change it by adding something to it possibly changing it's hashcode() return value. I heard that this is would not work but no one explained why. I was wondering if someone could tell me how I can do this most efficiently.

HashSet在内部使用具有与键相同的值的HasMap。对于将对象放入Hashset,jvm fill首先计算对象的哈希码,然后基于该哈希码选择相应的存储桶并放入对象,因此如果您在更改哈希码之后将对象放入哈希集中,您将无法正确获取其位置。因此,如果您确实要删除该元素,最好从哈希集中删除该对象,更改其值,然后再次放回

It wont work because the hashcode is the key to find the object, if you modify the object in such a way you change it's hashcode you won't be able to find it again.

It is like the entry in a dictionary, if you change it you won't find it again. Does it makes sense?

If you want to perform a lookup, you should be using a Map. If you want to change the key (or an element of a Set) you have to remove it first and add it again. For this reason your key should only have immutable fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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