class temp {
int id;
public int getId() {
return id;
}
temp(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
temp other = (temp) obj;
if (id != other.id)
return false;
return true;
}
}
public class testClass {
public static void main(String[] args) {
temp t1 = new temp(1);
temp t2 = new temp(1);
System.out.println(t1.equals(t2));
Set<temp> tempList = new HashSet<temp>(2);
tempList.add(t1);
tempList.add(t2);
System.out.println(tempList);
}
Run Code Online (Sandbox Code Playgroud)
该程序将两个元素添加到Set.起初我很震惊,因为在添加set方法的同时,调用了equals方法.
但后来我覆盖了hashCode方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后它没有添加.这是令人惊讶的,因为Set和add()方法的Javadoc说它在添加到Set时只检查equals().
这是add()的javadoc:
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
Run Code Online (Sandbox Code Playgroud)
然后我意识到HashSet是作为HashMap实现的,在地图中,对象的hashCode用作键.所以,如果你不重写hashCode,它会使用不同的键来处理它们.
这不应该在add()方法或HashSet的文档中吗?
Kal*_*lja 20
有点记录.请参阅java.lang.Object的文档,其中包含hashCode():
如果两个对象根据equals(Object)方法相等,则对两个对象中的每一个调用hashCode方法必须生成相同的整数结果.
此外,该Object.equals(Object)方法的文档中还包含以下内容:
请注意,通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等对象必须具有相等的哈希代码.
换句话说,如果你的班级何时instanceA.equals(instanceB) == true和instanceA.hashCode() != istanceB.hashCode()你实际上违反了Object类的合同.
Jac*_*ack 14
只需看看equals()文档:
请注意,通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等对象必须具有相等的哈希代码.
事实是,equals()并且hashCode()有很强的联系.在使用其中一个时,应始终考虑两者以避免这些一致性问题.
| 归档时间: |
|
| 查看次数: |
15846 次 |
| 最近记录: |