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

后端 未结 6 1802
鱼传尺愫
鱼传尺愫 2020-12-02 01:38

Printing a char array does not display a hash code:

class IntChararrayTest{
    public static void main(String[] args){
        int intArray[] = {0,1,2};
            


        
6条回答
  •  我在风中等你
    2020-12-02 02:12

    The int array is an array of integers where as the char array of printable characters. The printwriter has the capability to print character arrays as this is how it prints string anyway. The printwriter will therefore print them like a string, without calling the toString() method to convert it to a string. Converting an int array to a string returns a hash code, explaining why you get that output.

    Take this for example:

    int[] ints = new int[] { 1, 2, 3 };
    char[] chars = new char[] { '1', '2', '3' }
    

    If you were to print both those sequences using the method you used, it would print the hash code of the int array followed by '123'.

提交回复
热议问题