![](/img/trans.png)
[英]Why does StringBuffer/StringBuilder not override equals or hashCode?
[英]Why does changing StringBuilder change its hashCode?
這是輸入。
public static void main(String[] args){
StringBuilder builder = new StringBuilder("hello");
printBuilder(builder);
// append
builder.append(" everyone");
printBuilder(builder);
builder.append(", what's up?");
printBuilder(builder);
}
private static void printBuilder(StringBuilder dataBuild){
StringBuilder build = new StringBuilder(dataBuild);
System.out.println("data = " + build);
System.out.println("length = " + build.length());
System.out.println("capacity = " + build.capacity());
int addressBuild = System.identityHashCode(build);
System.out.println("address = " + Integer.toHexString(addressBuild);
}
這是 output。
為什么地址與其他地址不同? 我雖然會是一樣的。 我嘗試了不同的方法,如插入、替換、charAt,但地址仍然不同。 誰能告訴我為什么?
在printBuild()
中,每次調用都會創建一個新的StringBuilder
。 每次都會為新構建器打印 hash:
int addressBuild = System.identityHashCode(build);
你不能合理地期待不同的結果。 如果您想每次都看到相同的 hash,請刪除以下行:
StringBuilder build = new StringBuilder(dataBuild);
直接對輸入參數dataBuild
進行操作:它作為引用傳入。
詳細說明: System.identityHashCode
產生的結果只有在對象相同時才能保證相同(如==
,而不是equals()
)。 當然,與任何 hash 一樣,兩個不相等的對象可能具有相同的 hash,但 function 確實會嘗試減少重疊。 正如預期的那樣,結果通常基於memory 位置,盡管它通常不是 memory 位置本身。
System#identityHashCode
不返回 object 的地址。
返回給定 object 的相同 hash 代碼,與默認方法 hashCode() 返回的代碼相同,無論給定對象的 class 是否覆蓋 hashCode()。 null 參考的 hash 代碼為零。
class 的每個 object 具有不同的 hash 代碼。 由於每次調用 printBuilder 都會創建一個新的printBuilder
,因此您將獲得不同的 hash 代碼。
注意:對於具有相同 hash 代碼的引用,使用==
的比較返回true
。
class Main {
public static void main(String[] args) {
Boolean b1 = true;
Boolean b2 = Boolean.valueOf("true");
System.out.println(System.identityHashCode(b1));
System.out.println(System.identityHashCode(b2));
System.out.println(b1 == b2);
String s1 = "Hello";
String s2 = s1;
String s3 = new String("Hello");// Creates a new object and hence s3 will have a different hash code
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
System.out.println(s1 == s2);
System.out.println(System.identityHashCode(s3));
System.out.println(s2 == s3);
}
}
Output:
992136656
992136656
true
511833308
511833308
true
1297685781
false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.