gpt4 book ai didi

java - 更改字段值时的 HashSet 行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:44 25 4
gpt4 key购买 nike

我刚刚做了以下代码:

import java.util.HashSet;
import java.util.Set;


public class MyClass {

private static class MyObject {
private int field;

public int getField() {
return field;
}

public void setField(int aField) {
field = aField;
}

@Override
public boolean equals(Object other) {
boolean result = false;
if (other != null && other instanceof MyObject) {
MyObject that = (MyObject) other;
result = (this.getField() == that.getField());
}
return result;
}

@Override
public int hashCode() {
return field;
}
}

public static void main(String[] args) {
Set<MyObject> mySet = new HashSet<MyObject>();
MyObject object = new MyObject();
object.setField(3);
mySet.add(object);
object.setField(5);
System.out.println(mySet.contains(object));
MyObject firstElement = mySet.iterator().next();
System.out.println("The set object: " + firstElement + " the object itself: " + object);
}

}

它打印:

false
The set object: MyClass$MyObject@5 the object itself: MyClass$MyObject@5

基本上意味着 object 不被认为在集合中,而它的实例本身显然在集合中。这意味着如果我在集合中插入一个对象,然后更改参与 hashCode 方法计算的字段的值,那么 HashSet 方法将抢占工作正如预期的那样。这不是可能错误的太大来源吗?人们如何为此类案件辩护?

最佳答案

以下是 Set API 的引用。它解释了一切。

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.

http://docs.oracle.com/javase/7/docs/api/java/util/Set.html

关于java - 更改字段值时的 HashSet 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com