gpt4 book ai didi

java - 在 Java 中打印字符数组

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:27 24 4
gpt4 key购买 nike

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

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

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

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

我原以为它会打印为字符串,而且我确定为什么会出现这种情况。有什么解释吗?

最佳答案

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

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

""+ 确实是伪造的,应该删除。

以下是您得到所得到的原因。


System.outPrintStream . println() 重载了 println(char[] x) :

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


""+ 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.

JLS 5.1.11 String Conversion说:

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

toString() 没有为数组定义,所以 Object.toString()方法被调用:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character '@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

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

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

关于java - 在 Java 中打印字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com