Whenever I try to print the char arrays to the console, I'm getting the result in integer format, but whenever I try to print integer arrays to the console, I'm getting the result in hashcode format. Could anyone please tell me why?
char[] arr={'4','5','6'};
System.out.println(arr); //456
int[] arr={4,开发者_如何转开发5,6};
System.out.println(arr) //[I@3e25a5]
java.io.PrintStream
(the class of System.out
) has a special print
-method for char[]
, but not for int[]
. So for the char[]
, this special method is used, while int[]
is printed via the generic version, which prints the hashcode (or, to be more precise, the result of String.valueOf()
called with the object as parameter).
Simply because there's no method for which handles int[]
specially. It would be printed by String#valueOf()
instead which implicitly calls Object#toString()
. If the Object#toString()
isn't overridden in the given object type, then the following will get printed (as per the aforelinked API).
getClass().getName() + '@' + Integer.toHexString(hashCode())
The int[]
class has a name of [I
.
To achieve what you want, you need Arrays#toString()
instead:
int[] arr = {4, 5, 6};
System.out.println(Arrays.toString(arr)); // [4, 5, 6]
In the first case the character array is just used like a string (which is in fact also just an array of characters).
In the second it has no overload for the type of integer array and just prints out the object reference.
I think that the first one is treated as a CharSequence... like a String.
精彩评论