在 Java 中打印字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36366772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:47:03  来源:igfitidea点击:

Printing char arrays in Java

javaarrays

提问by Toby L.

If I print out a char array normally

如果我正常打印出一个字符数组

char[] c = new char[]{'3','b','o'};
System.out.println(c); //prints 3bo

the output is a string. However, if I concatenate a String it prints the array memory location.

输出是一个字符串。但是,如果我连接一个字符串,它会打印数组内存位置。

System.out.println("" + c); //prints [C@659e0bfd

I would have expected it to print as a String and I'm sure why this behavior happens. Any explanations?

我原以为它会打印为字符串,我确定为什么会发生这种行为。有什么解释吗?

采纳答案by Andreas

Solution is to use new String(c):

解决方案是使用new String(c)

System.out.println("" + new String(c));

And the "" +is really bogus and should be removed.

而且"" +真的是假的,应该删除。

Below is why you get what you get.

下面是为什么你得到你所得到的。



System.outis a PrintStream. println()has an overload for println(char[] x):

System.out是一个PrintStreamprintln()有一个重载println(char[] x)

Prints an array of charactersand then terminate the line. This method behaves as though it invokes print(char[])and then println().

打印一个字符数组,然后终止该行。此方法的行为就像它调用print(char[])然后println()



"" + cis string concatenation, which is defined in JLS 15.18.1 String Concatenation Operator +:

"" + c字符串连接,在JLS 15.18.1 String Concatenation Operator 中+定义:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

如果只有一个操作数表达式是 type String,则在运行时对另一个操作数执行字符串转换(第5.1.11 节)以生成字符串。

And JLS 5.1.11 String Conversionsays:

JLS 5.1.11字符串转换说:

[...] the conversion is performed as if by an invocation of the toString methodof the referenced object with no arguments [...]

[...] 执行转换就像调用引用对象的 toString 方法一样,没有参数 [...]

toString()is not defined for arrays, so the Object.toString()method is invoked:

toString()未为 arrays 定义,因此Object.toString()调用该方法:

The toStringmethod for class Objectreturns a string consisting of the name of the classof which the object is an instance, the at-signcharacter '@', and the unsigned hexadecimal representation of the hash codeof the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

toStringclass的方法Object返回一个字符串,该字符串由对象是其实例的类名称at 符号字符 ' @' 和对象哈希码的无符号十六进制表示组成。换句话说,此方法返回一个等于以下值的字符串:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

Which is why you get something like [C@659e0bfdwhen you do string concatenation.

这就是为什么[C@659e0bfd在进行字符串连接时会得到类似结果的原因。

回答by DarkJade

In the first case, you have an instance in a print stream. In the second case, you have the array concatenated with a string. If you did something like

在第一种情况下,您在打印流中有一个实例。在第二种情况下,您将数组与字符串连接在一起。如果你做了类似的事情

System.out.println("" + c[0]); // or whatever number you put in there

It would print some of the string you are looking for.

它会打印您正在寻找的一些字符串。

String stringfromArray = "" + new String(c);

,would function more like what you are looking for in the second part of your question, but you don't need to do the "" +part.

, 会更像您在问题的第二部分中寻找的功能,但您不需要执行该"" +部分。

回答by yerlilbilgin

When you call System.out.println(char []array) the PrintStream class writes the chars (one of its overloads handles the job).

当您调用 System.out.println(char []array) 时,PrintStream 类会写入字符(它的重载之一处理该作业)。

But for the second case, java converts the char array to string by calling its toString method which is a regular array toString method. And concatenating it with empty string, you receive the array signature [C*.... This is an expected and normal behavior.

但是对于第二种情况,java 通过调用它的 toString 方法将 char 数组转换为字符串,该方法是一个常规数组 toString 方法。并将它与空字符串连接起来,您会收到数组签名 [C*.... 这是预期的正常行为。

EditHere is the PrintStream code that gets eventually called when you call 'System.out.println(c)':

编辑这是当您调用“System.out.println(c)”时最终调用的 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;
    }
}

回答by Shear Plane

One call is PrintStream.println(char[])the other call is PrintStream.println(String).

一个电话是PrintStream.println(char[])另一个电话PrintStream.println(String)

This is because the JVM first evaluates "" + c. This is done by evaluating "" + c.toString()which is identically to c.toString().

这是因为 JVM 首先评估"" + c. 这是通过评估"" + c.toString()which 与 相同来完成的c.toString()

So, your calls are equivalent to:

所以,你的电话相当于:

System.out.println(c);
System.out.println(c.toString());

And these two calls are different.

并且这两个调用是不同的。

回答by yang

the array of char can directly output,because it will insist on outputing untill the value is nullAnd the array of char cannot use the way of toString(),because it will only get the memory location,so you can new String(the array of char)

char数组可以直接输出,因为它会坚持输出直到值为null而char数组不能使用toString()的方式,因为它只会获取内存位置,所以你可以new String(数组字符)

回答by Havoc Lee

All of the above are great solutions and explanations. However, there is also another way to 'bypass' this problem:

以上都是很好的解决方案和解释。但是,还有另一种方法可以“绕过”这个问题:

You can use two print statements, more specifically,

您可以使用两个打印语句,更具体地说,

System.out.print("");
System.out.print(c);

This way they will be on the same line (b/c print does not use line feed to go to the next line) and you will not have to deal with any complications because of String concatenations.

这样它们将在同一行上(b/c 打印不使用换行符转到下一行)并且您不必处理由于字符串连接而引起的任何复杂情况。

For more information, see the Print Stream Documentation by Oracle . Here is the documentation portion for print when a char[] is passed as the argument:

有关更多信息,请参阅Oracle打印流文档。这是当 char[] 作为参数传递时用于打印的文档部分:

public void 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 write(int) method.

公共无效打印(char [] s)

打印字符数组。字符根据平台默认的字符编码转换为字节,这些字节的写入方式与 write(int) 方法完全相同。

回答by KayV

Simplest form is

最简单的形式是

Arrays.toString(c);

and if it is a 2D array, then use deepToString as follows:

如果是二维数组,则使用 deepToString 如下:

Arrays.deppToString(twoDArray);