![](/img/trans.png)
[英]Why is equals() not called while adding to HashSet and hashCode matches?
[英]Why hashcode is called in this example?
有人可以解釋為什么在下面的示例中調用hashCode嗎?
import java.util.List;
public class JSSTest extends Object{
public static void main(String args[]){
JSSTest a = new JSSTest();
JSSTest b = new JSSTest();
List<JSSTest> list = new java.util.ArrayList<JSSTest>();
list.add(a);
list.add(b);
System.out.println(list.get(0));
System.out.println(list.get(1));
}
@Override
public boolean equals(Object obj){
System.out.println("equals");
return false;
}
@Override
public int hashCode(){
System.out.println("hashCode");
return super.hashCode();
}
}
結果:
hashCode 0
JSSTest@1bab50a
hashCode 0
JSSTest@c3c749
默認的toString()
實現調用hashCode
。 這與列表無關。
這是一個相當少的復制:
public class JSSTest {
public static void main(String args[]){
JSSTest test = new JSSTest();
// Just to show it's not part of creation...
System.out.println("After object creation");
test.toString();
}
@Override
public boolean equals(Object obj){
System.out.println("equals");
return false;
}
@Override
public int hashCode(){
System.out.println("hashCode");
return super.hashCode();
}
}
(您也可以覆蓋toString()
以顯示之前/超級調用/之后的詳細信息。)
它記錄在Object.toString()
中:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. 換句話說,此方法返回一個等於以下值的字符串:
getClass().getName() + '@' + Integer.toHexString(hashCode())
System.out.println(list.get(0));
我相信它是所有對象都具有的 Object.toString() 方法的一部分,除非您在自己的 class 中覆蓋 toString()。 試試看。
因為Object
中的toString()
實現調用它..
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
覆蓋toString
,它不會被調用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.