Java開發中巧妙實現將byte[]陣列轉化為String型別
很多人在Java程式設計時,總是喜歡用一下方法將陣列轉為字串:(a為byte陣列)
String s=a.toString();
可是每次返回的時候,新手看來返回的結果是亂碼,比如說我,寫RSA演算法時,沒有注意,就以為是解密出來的亂碼(哈哈哈),但其實[[email protected] 為棧地址值,這個時候要知道對於返回一個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:[
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: etClass().getName() + ‘@’ + Integer.toHexString(hashCode())
大體意思就是類Object的toString方法返回一個字串,該字串由物件為例項的類的名稱、符號符號符號“@”和物件程式碼的無符號十六進位制表示組成。換句話說,此方法返回一個字串。
因此,下次不要用錯方法咯!