如果char数组是Java中的Object,为什么打印它不显示其哈希码? [英] If a char array is an Object in Java, why does printing it not display its hash code?
问题描述
打印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
为什么整数数组打印为哈希码而不是char数组?
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
(这是系统的类型。 out
instance)对于字符数组有一个特殊版本的 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.
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,为什么打印它不显示其哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!