打印 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.
这篇关于如果 char 数组是 Java 中的 Object,为什么打印它不显示其哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
“Char 不能被取消引用"错误quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch 语句 - 是“或"/“和"可能的?Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java替换字符串特定位置的字符?Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
具有 int 和 char 操作数的三元表达式的类型是什么What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
读取文本文件并存储出现的每个字符Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
为什么我需要在 byte 和 short 上显式转换 char 原语Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)