问题描述
引用型变量存储的是对象实例的地址值,如果直接打印变量,输出的应该是地址值。
数值型数组如int型数组:初始化后直接打印数组名,输出的是地址值。
但是:char类型数组无论是new还是直接赋值初始化,直接打印后显示的居然不是地址值,而是数组内容。而ArrayList也会输出值而不是地址值
原因分析
char类型的数组就相当于一个字符串。
因为输出流System.out是PrintStream对象,PrintStream有多个重载的println方法,其中一个就是public void println(char[] x);
直接打印字符数组的话,不像int[]等其他数组,它会直接调用这个方法来打印,因而可以打印出数组内容,而不是地址。
char类型数组输出总结
直接输出数组名:将数组以字符串形式打印;
输出前面加字符:输出的是地址;
输出前面加字符的情况下想要输出数组内容:Arrays.toString(ch),数组内容将以数组形式输出:
字符型数组源代码
public void println(char x[]) {
synchronized (this) {
print(x);
newLine();
}
}
public void print(char s[]) {
write(s);
}
private void write(char buf[]) {
try {
synchronized (this) {
ensureOpen();//确认输出流是否打开了
textOut.write(s);//就是一个bufferWriter,写入到缓冲区
textOut.flushBuffer();//刷新缓存区
charOut.flushBuffer();//OutputStreamWriter
if (autoFlush && (s.indexOf('\n') >= 0))
out.flush();//这里就是与char数组的区别,他直接把String s刷新到了控制台的输出流中,但是记住他没有和toString方法相关联
}
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
非字符型数组源代码(包括ArrayList)
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();//除了char数组,其他类型数组最后都会调用obj.toString,也就输出了地址。
}
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
private void write(String s) {
try {
synchronized (this) {
ensureOpen();
textOut.write(s);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush && (s.indexOf('\n') >= 0))
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
其中ArrayList继承的AbstractCollection.class中重写了toString方法,所以会输出所有值,
AbstractCollection.class
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}