2

I am having this problem with a LinkedHashSet and its contains method. Let me summarize it to you.

I have this class C1 with 4 String attributes, its respective getters and setters as well as equals(), and hashCode() methods as given by default by eclipse.

Then I have another class C2 that has 1 attribute of type LinkedHashSet with the getSet() method for accessing it.

When I create 1 instance of a C1 class (say object c1) and add it to an instance c2 of class C2, everything is fine... I do:

C1 c1 = new C1("a", "b", "c", "d");
C2 c2 = new C2();
c2.getSet().add(c1);

Now if I set a different value to the first attribute of c1, with the appropriate set method, and then I try to check if c2.getSet() contains element c1... but it always returns false. But the hashcode of the object changed and the one within the set is the same, and apparently, the equals test in the contains method is failing...

Does anyone understand what is happening here? What can be wrong? Equals and HashCode()?

Thanks in advance, cheers

4

2 回答 2

2

当您将对象添加到哈希集(或哈希映射或任何使用哈希查找对象的集合)时,集合类会根据为对象计算的哈希码将对象放入“桶”中。在此之后,您更改对象的一个​​属性,因此下次计算该对象的哈希码将不同。但是,该对象位于与旧哈希码对应的位置/存储桶中。因此,当您尝试查找具有更改的属性和哈希码的对象时,该集合会在错误的存储桶中查找并发现它是空的。哈希码或equals方法都没有错。您在这里犯的错误是:一旦将对象放入哈希集或哈希映射中,就永远不要更改用于哈希映射计算的对象的字段。作为最佳实践,

于 2013-10-28T17:43:23.260 回答
0

LinkedHashSet 集合不会跟随你的内部修改。通过更改 c1 内容,我认为您更改了对象的 hashCode。因此,当您调用 contains 时,LinkedHashSet 无法检索它。

于 2013-10-28T17:32:59.543 回答