热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在Java中返回Hashset中的对象-ReturningaObjectinaHashsetinJava

HiIhaveaHashSetlikethefollowinginaclasscalledMemory:嗨,我在一个名为Memory的类中有如下的HashSet:Set&

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

嗨,我在一个名为Memory的类中有如下的HashSet:

Set ideas = new HashSet();

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.

泛型类型“Idea”是我编写的另一个类,它具有hashcode()和equals()覆盖。我希望能够在HashSet中获取(而不是删除)一个Idea对象,然后通过添加一些东西来改变它,可能会改变它的hashcode()返回值。我听说这不行,但没有人解释原因。我想知道是否有人能告诉我如何才能最有效地做到这一点。

3 个解决方案

#1


1  

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.

如果要执行查找,则应使用Map。如果要更改键(或Set的元素),则必须先将其删除并再次添加。因此,您的密钥应该只有不可变字段。

#2


2  

HashSet internally uses HasMap with value same as the key.For putting an object to Hashset, jvm fill first calculate the hashcode of the object and based on that hashcode, corresponding bucket is selected and object is put.So if you are changing the hashcode after putting the object into hashset,you wont be able to get its location correctly.So if you really want to remove the element, better remove the object from hashset change its value and then put it back again

HashSet在内部使用HasMap,其值与key相同。为了将对象放入Hashset,jvm fill首先计算对象的hashcode,并根据该hashcode,选择相应的bucket并放置对象。如果你要更改hashcode之后将对象放入hashset,你将无法正确获取其位置。如果你真的想要删除元素,最好从hashset中删除对象更改其值,然后再将其重新放回

#3


1  

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?

它就像字典中的条目,如果你改变它,你将不会再找到它。这有道理吗?


推荐阅读
author-avatar
GRIROR格雷尔
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有