Java中如何正確的將byte[]數組轉化為String類型?


   很多人在編程時,總是喜歡用一下方法將數組轉為字符串:(a為byte數組)

    String s=a.toString();

可是每次返回的時候,新手看來返回的結果是亂碼,比如說我,寫RSA算法時,沒有注意,就以為是解密出來的亂碼(哈哈哈),但其實[B@1b6d3586 為@+hash值,這個時候要知道對於返回一個String對象,new一個是基本上不會錯的,測試代碼如下:

 

1         Scanner scan=new Scanner(System.in);
2         String s="ghhhh";
3         byte[]a=s.getBytes();
4         String s1=a.toString();
5         String s2=new String(a);
6         System.out.println("s1:"+s1);
7         System.out.println("s2:"+s2);            

 

測試結果:

1 s1:[B@1b6d3586
2 s2:ghhhh

可以看到s1所對應的方法只是返回hash值,而s2才真正返回了a的實體值。

這是因為,String java.lang.Object.toString()返回的確實是hash值,介紹如下:

 

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方法返回一個字符串,該字符串由對象為實例的類的名稱、符號符號符號“@”和對象哈希代碼的無符號十六進制表示組成。換句話說,此方法返回一個字符串。

  因此,下次不要用錯方法咯!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM