首页 > 代码库 > Java 数组输出

Java 数组输出

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 包装了 charOut
textOut.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 数组的每个字符挨个输出到控制台中。

Java 数组输出