【发布时间】:2015-03-17 17:40:55
【问题描述】:
我有一个类,它在实例化时为其对象创建一个唯一 ID,如下所示:
public class Foo {
private final static AtomicInteger UNIQUE_ID = new AtomicInteger(0);
private final int id;
private final String name;
private final int hashcode;
public Foo(String name) {
id = UNIQUE_ID.GetAndIncrement();
this.name = name;
int result = 17;
int result = 31 * result + id;
int result = 31 * result + name.hashCode();
hashcode = result;
}
public int getInstanceID() { return id; }
现在我想以这种方式实现 hashCode 和 equals:
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Foo))
return false;
Foo other = (Foo) obj;
return other.getInstanceID == getInstanceID();
}
public int hashCode() { return hashcode; }
}
如果我只比较对象的 ID 而不考虑任何其他可能与一个 Foo 不同的字段,这是否被认为是不好的做法?另外,我应该仍然关注 hashcode 函数中的每个字段还是只使用 id?
【问题讨论】:
标签: java equals uniqueidentifier identifier