2014-12-19 25 views
2

我想不通爲什麼調用getBytes()構造一個字符串兩次返回是不相等的()兩個字節數組:Java的String的getBytes nondetermism

final String aString = "hello world"; 
System.out.println(aString.getBytes()); 
System.out.println(aString.getBytes()); 
System.out.println(aString.getBytes()); 

打印:

[[email protected] 
[[email protected] 
[[email protected] 

例如以下斷言總是失敗:

Assert.assertEquals(aString.getBytes(), aString.getBytes()); 

doc,我沒想到的任何確定性!我錯過了什麼?

當轉換回字符串,結果是預期的,所以我最好的猜測是一些未初始化的填充位?

I.e.以下斷言總是通過:

Assert.assertEquals(new String(aString.getBytes()), new String(aString.getBytes())); 
+0

組合http://stackoverflow.com/questions/4479683/java-arrays-printing-out-weird-numbers-and-text和http://stackoverflow.com/questions/8777257/equals-vs-array -equals-in-java –

回答

4

的問題是,getBytes()返回byte[],和陣列Object S IN的Java。但是,這些數組對象不會覆蓋Object's toString() method,它負責您看到的輸出。

換句話說,此方法返回一個字符串等於的值:

getClass().getName() + '@' + Integer.toHexString(hashCode()) 

輸出包括的哈希碼,這對於每個對象不同,即使內容是相同。

使用Arrays.toString以獲得具有陣列內容的String,例如,

System.out.println(Arrays.toString(aString.getBytes())); 

3次。新輸出:

[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 
+0

謝謝,這解釋了println的不同輸出,但爲什麼assertEqual返回false? – Marco

+0

雖然我的答案解釋了字符串輸出,但Sotirios的答案解釋了爲什麼更好,包括解決方案。 – rgettman