Java 數組輸出
Java 數組輸出一般都是用循環輸出,例如(code1):
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
但是,對於 char[] 類型的數組,可以使用一條輸出語句輸出,例如(code2):
char[] chs = { 'a', 'b', 'c', 'd' };
System.out.println(chs);
注意 code1 和 code2 中兩條打印語句的區別:
System.out.print(arr[i]);//code1
System.out.println(chs);//code2
打印 int 數組 arr 的時候沒有換行,因爲是 System.out.print(); 打印 char 數組 chs 的時候,中間也沒有換行,就好像是把 chs 數組內容當成了一個字符串打印一樣。
char 數組之所以可以這樣直接輸出,是因爲源碼中的實現:
void java.io.PrintStream.println(char[] x)
/**
* Prints an array of characters and then terminate the line. This method
* behaves as though it invokes <code>{@link #print(char[])}</code> and
* then <code>{@link #println()}</code>.
*
* @param x an array of chars to print.
*/
public void println(char x[]) {
synchronized (this) {
print(x);
newLine();
}
}
void java.io.PrintStream.print(char[] s)
/**
* Prints an array of characters. The characters are converted into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param s The array of chars to be printed
*
* @throws NullPointerException If <code>s</code> is <code>null</code>
*/
public void print(char s[]) {
write(s);
}
void java.io.PrintStream.write(char[] buf)
/*
* The following private methods on the text- and character-output streams
* always flush the stream buffers, so that writes to the underlying byte
* stream occur as promptly as with the original PrintStream.
*/
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();
}
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
textOut 是 BufferedWriter 對象,代表着向控制檯輸出信息的輸出流對象。charOut 是 OutputStreamWriter 對象,是用來將字節轉換成字符的轉換流對象。textOut 包裝了 charOuttextOut.write(buf);調用到以下方法:
/**
* Writes an array of characters.
*
* @param cbuf
* Array of characters to be written
*
* @throws IOException
* If an I/O error occurs
*/
public void write(char cbuf[]) throws IOException {
write(cbuf, 0, cbuf.length);
}
該方法就是將 char 數組的每個字符挨個輸出到控制檯中。
總結一句話,其實 System.out.println(c); 就是將 c 數組的每個字符挨個輸出到控制檯中。