如果 char 数组是 Java 中的 Object,为什么打印它不显示其哈希码?

2022-01-12 00:00:00 arrays char java

打印 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.

相关文章