一般直觀array如果直接使用System.out.println(aryName);
會印出array在memory address
但忽然發現char[] 竟然會直接印出array內的元素
好奇使然發現print中竟把char[]跟其他array(Object)切分開
public void print(char s[]) {
write(s);
}
private void write(char[] buf) {
try {
synchronized (this) {
ensureOpen();
textOut.write(buf);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush) {
for (int i = 0; i < buf.length; i++)
if (buf[i] == '\n') {
out.flush();
break;
}
}
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
trouble = true;
}
}
public void print(Object obj) {
write(String.valueOf(obj));
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
看起來是使用的write方法所傳入的實際參數不同,但如果把city強制轉型為字串(前方加" "、toString()),就會變成輸出memory address
import java.util.Arrays;
public class ArrayOperate2 {
public static void main(String[] args) {
char [] city = {'D','B','A'};
System.out.println(city); // DBA
System.out.println(" "+city); // [C@5fd0d5ae
System.out.println(" "+ new String(city)); // DBA
System.out.println(" "+city.toString()); // [C@5fd0d5ae
System.out.println(city.toString()); // [C@5fd0d5ae
System.out.println(Arrays.toString(city)); // [D, B, A]
}
}
今天發現這事覺得真有趣,最近在看SOLID設計原則,它帶給我對敏捷開發有不一樣看法,顛覆我對字面解讀