Why does the toString method in java not seem to work for an array

后端 未结 9 1411
灰色年华
灰色年华 2020-11-22 12:25

I want to convert a character array to a string object using the toString() method in java. Here is a snippet of the test code I used:

import java.util.Array         


        
相关标签:
9条回答
  • 2020-11-22 12:49
    char[] Array = { 'a', 'b', 'c', 'd', 'e', 'f' };
    System.out.println(Array);
    

    It should print abcdef.

    0 讨论(0)
  • 2020-11-22 12:54

    The default implementation of the toString method of the char [] class returns a String representation of the base address of the array, which is what is being printed here. We cannot change it, since the class of char [] is not extendable.

    0 讨论(0)
  • 2020-11-22 12:56

    Arrays don't override toString. There's a static method: java.util.Arrays.toString that should solve your problem.

    import java.util.Arrays;
    class toString {
        public static void main(String[] args){
            char[] Array = {'a', 'b', 'c', 'd', 'e', 'f'};
            System.out.println(Arrays.toString(Array));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 12:56

    There is a spelling mistake of "Array.toString()" to "Arrays.toString(Array)" I guess so, and instead of writing name.toString(), pass the name as an argument and Write as above.

    0 讨论(0)
  • 2020-11-22 12:57

    Just use the following commands to get your abcdef array printed

        String a= new String(Array);
    
        System.out.println(a);
    

    there you have it problem solved !! now regarding why is printing the other stuff i think those guys above put some useful links for that. Ok gotta go !!

    0 讨论(0)
  • 2020-11-22 12:58

    Because a char array is an array of primitives and toString() will give you it's default (which is a hash of the object). Some classes will implement toString() to do cooler things, but primitaves will not.

    0 讨论(0)
提交回复
热议问题