今天被同事問到Java equals的問題,發現觀念已經有點模糊了…老啦
只記得數字就用==,字串就用equals,至於原因已經還給老師了
Sample:
一開始真的有點打結,不同的物件怎麼會有相同的hashCode…是我的記憶有了錯誤嗎XD
想不通只好各種解釋…
String s1 = new String("ABC"); String s2 = new String("ABC"); System.out.println("s1." + s1 + ".hashCode:" + s1.hashCode()); System.out.println("s2." + s2 + ".hashCode:" + s2.hashCode()); if(s1.equals(s2)){ System.out.println("s1 is equals s2 !"); }else{ System.out.println("s1 is not equals s2 !"); } if(s1 == s2){ System.out.println("s1 = s2 !"); }else{ System.out.println("s1 != s2 !"); } Object o1 = new Object(); Object o2 = new Object(); System.out.println("o1." + o1 + ".hashCode:" + o1.hashCode()); System.out.println("o2." + o2 + ".hashCode:" + o2.hashCode()); if(o1.equals(o2)){ System.out.println("o1 is equals o2 !"); }else{ System.out.println("o1 is not equals o2 !"); } if(o1 == o2){ System.out.println("o1 = o2 !"); }else{ System.out.println("o1 != o2 !"); }
Console log:
s1.ABC.hashCode:64578 s2.ABC.hashCode:64578 s1 is equals s2 ! s1 != s2 ! o1.java.lang.Object@7852e922.hashCode:2018699554 o2.java.lang.Object@4e25154f.hashCode:1311053135 o1 is not equals o2 ! o1 != o2 !
後來才想到可以看一下Source Code
原來String有去覆寫hashCode()及equals()
hashCode()改成只要相同valeu就會得到相同的hashCode
equals()也是改成比較value是否相同
而原Object的hashCode()應該是每個不同的物件都會有不同的hashCode
原Object的equals()則是直接回傳==的結果~
String source code:
private int hash; // Default to 0 public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
留言
張貼留言