很多人在編程時,總是喜歡用一下方法將數組轉為字符串:(a為byte數組)
String s=a.toString();
可是每次返回的時候,新手看來返回的結果是亂碼,比如說我,寫RSA算法時,沒有注意,就以為是解密出來的亂碼(哈哈哈),但其實[B@1b6d3586 為棧地址值,這個時候要知道對于返回一個String對象,new一個是基本上不會錯的,測試代碼如下:
Scanner scan=new Scanner(System.in); String s="ghhhh"; byte[]a=s.getBytes(); String s1=a.toString(); String s2=new String(a); System.out.println("s1:"+s1); System.out.println("s2:"+s2);
測試結果:
1 s1:[B@1b6d3586 2 s2:ghhhh
可以看到s1所對應的方法只是返回的byte數組的地址值,而s2才真正返回了a的實體值。
這是因為,String JAVA.lang.Object.toString()返回的確實是地址值,介紹如下:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
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. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
大體意思就是類Object的toString方法返回一個字符串,該字符串由對象為實例的類的名稱、符號符號符號“@”和對象哈希代碼的無符號十六進制表示組成。換句話說,此方法返回一個字符串。