問題描述
打印 char 數組不顯示哈希碼:
Printing a char array does not display a hash code:
class IntChararrayTest{
public static void main(String[] args){
int intArray[] = {0,1,2};
char charArray[] = {'a','b','c'};
System.out.println(intArray);
System.out.println(charArray);
}
}
輸出:
[I@19e0bfd
abc
為什么整數數組打印為哈希碼而不是字符數組?
Why is the integer array printed as a hashcode and not the char array?
推薦答案
首先,char 數組是 Java 中的 Object,就像任何其他類型的數組一樣.只是打印方式不同.
First of all, a char array is an Object in Java just like any other type of array. It is just printed differently.
PrintStream
(它是 System.out
實例的類型)有一個特殊版本的 println
用于字符數組 - public void println(char x[])
- 所以它不必為該數組調用 toString
.最終調用public void write(char cbuf[], int off, int len)
,將數組的字符寫入輸出流.
PrintStream
(which is the type of the System.out
instance) has a special version of println
for character arrays - public void println(char x[])
- so it doesn't have to call toString
for that array. It eventually calls public void write(char cbuf[], int off, int len)
, which writes the characters of the array to the output stream.
這就是為什么為 char[]
調用 println 的行為不同于為其他類型的數組調用它的原因.對于其他數組類型,選擇 public void println(Object x)
重載,它調用 String.valueOf(x)
,它調用 x.toString()
,它為 int 數組返回類似 [I@19e0bfd
的內容.
That's why calling println for a char[]
behaves differently than calling it for other types of arrays. For other array types, the public void println(Object x)
overload is chosen, which calls String.valueOf(x)
, which calls x.toString()
, which returns something like [I@19e0bfd
for int arrays.
這篇關于如果 char 數組是 Java 中的 Object,為什么打印它不顯示其哈希碼?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!