java byte類型相加:javabyte數組轉string

很多人在編程時,總是喜歡用一下方法將數組轉為字符串:(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的實體值。

Java編程中如何正確的將byte「」數組轉化為String類型?

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

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/220646.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 12:13
下一篇 2024-12-09 12:13

相關推薦

發表回復

登錄後才能評論