Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

If a char array is an Object in Java, why does printing it not display its hash code?

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);
    }
}

output :

[I@19e0bfd
abc

Why is the integer array printed as a hashcode and not the char array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, a char array is an Object in Java just like any other type of array. It is just printed differently.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...