問題描述
這就是問題所在.這段代碼:
String a = "0000";System.out.println(a);char[] b = a.toCharArray();System.out.println(b);
返回
<上一頁>00000000
但是這段代碼:
String a = "0000";System.out.println("字符串 a:" + a);char[] b = a.toCharArray();System.out.println("char[] b:" + b);
返回
<上一頁>字符串 a:0000字符 [] b: [C@56e5b723
世界上到底發生了什么?似乎應該有一個足夠簡單的解決方案,但我似乎無法弄清楚.
當你說
System.out.println(b);
它導致調用 print(char[] s)
然后 println()
print(char[] s)
的 JavaDoc 說:
打印一個字符數組.字符轉換為字節根據平臺的默認字符編碼,而這些字節完全按照 write(int) 方法的方式寫入.
所以它會逐字節打印出來.
當你說
System.out.println("char[] b: " + b);
這會導致調用 print(String)
,因此您實際上正在做的是將 String
附加到 Object
它在 Object
上調用 toString()
- 這與默認情況下的所有 Object
以及在 Array 的情況下一樣
,打印引用的值(內存地址).
你可以這樣做:
System.out.println("char[] b: " + new String(b));
請注意,這是錯誤的",因為您不關心編碼并且使用系統默認值.盡早了解編碼.
Here's the problem. This code:
String a = "0000";
System.out.println(a);
char[] b = a.toCharArray();
System.out.println(b);
returns
0000 0000
But this code:
String a = "0000";
System.out.println("String a: " + a);
char[] b = a.toCharArray();
System.out.println("char[] b: " + b);
returns
String a: 0000 char[] b: [C@56e5b723
What in the world is going on? Seems there should be a simple enough solution, but I can't seem to figure it out.
When you say
System.out.println(b);
It results in a call to print(char[] s)
then println()
The JavaDoc for print(char[] s)
says:
Print an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
So it performs a byte-by-byte print out.
When you say
System.out.println("char[] b: " + b);
It results in a call to print(String)
, and so what you're actually doing is appending to a String
an Object
which invokes toString()
on the Object
-- this, as with all Object
by default, and in the case of an Array
, prints the value of the reference (the memory address).
You could do:
System.out.println("char[] b: " + new String(b));
Note that this is "wrong" in the sense that you're not paying any mind to encoding and are using the system default. Learn about encoding sooner rather than later.
這篇關于Java:帶有char數組的println給出亂碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!