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は、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;
}
次に、HashSetがHashMapとして実装されており、マップではオブジェクトのhashCodeがキーとして使用されていることに気付きました。したがって、hashCodeをオーバーライドしない場合は、異なるキーを使用してそれらを処理します。
これは、add()メソッドまたはHashSetのドキュメントに含めるべきではありませんか?