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);
}
这个程序将两个元素都添加到了Set中。一开始我很惊讶,因为在向集合中添加方法时,会调用equals方法。
但是后来我重写了hashCode方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
然后它没有被添加进去。这很奇怪,因为 Set 和 add() 方法的 Javadoc 声明在添加元素时只检查 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;
}
后来我意识到HashSet是以HashMap的形式实现的,在map中,对象的hashCode被用作键。因此,如果您不覆盖hashCode,它将使用不同的键对待它们。
add()方法或HashSet的文档中应该有这个说明吗?
hashCode()
相同时才会调用equals
,如果你重写了equals
,它不会调用默认的equals
。 - Peter Lawreyequals();
中使用 Object 类型参数,如果你仍然需要进行强制类型转换? - Asif Mushtaq