[英]string printing reference in java
I have this code where I am printing a string variable. 我有这个代码,我打印一个字符串变量。 The first output is showing what is expected but the second time it prints some unreadable output(I think its reference id). 第一个输出显示了预期的内容,但第二次显示了一些不可读的输出(我认为它的引用ID)。 Please explain: Why does this happen? 请解释:为什么会这样?
public class Str3 {
public String frontBack(String str) {
char c[] = str.toCharArray();
char temp = c[0];
c[0] = c[c.length - 1];
c[c.length - 1] = temp;
return c.toString();
}
public static void main(String args[]) {
Str3 s = new Str3();
String s1 = new String("boy");
System.out.println(s1);
String s2 = s.frontBack("boy");
System.out.println(s2);
}
}
Output: 输出:
boy 男孩
[C@60aeb0 [C @ 60aeb0
the frontToBack() method is calling toString()
on a character array object char[]
which is why you see the [C@60aebo
. frontToBack()方法在字符数组对象char[]
上调用toString()
,这就是为什么你看到[C@60aebo
。 Instead of calling toString()
return with new String(c);
而不是调用toString()
返回new String(c);
or String.valueOf(c)
或String.valueOf(c)
Array types in Java do not override Object#toString()
. Java中的数组类型不会覆盖Object#toString()
。 In other words, array types inherit Object
's implementation of toString()
which is just 换句话说,数组类型继承了Object
的toString()
实现
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
which is the output you see 这是你看到的输出
[C@60aeb0
If you want to see a representation of the contents of an array, use Arrays.toString(..)
. 如果要查看数组内容的表示,请使用Arrays.toString(..)
。
In your case, you seem to want to switch the first and last characters and return the corresponding string. 在您的情况下,您似乎想要切换第一个和最后一个字符并返回相应的字符串。 In that case, just create a new String
instance by passing the char[]
to the constructor. 在这种情况下,只需通过将char[]
传递给构造函数来创建一个新的String
实例。
You don't need to implement a custom class to do this. 您不需要实现自定义类来执行此操作。 The functionality is already in java. 该功能已经在java中。 This question has already been answered @ Reverse a string in Java (duplicate thread) 这个问题已经得到解答@ 在Java中反转一个字符串 (重复的线程)
use new String(c) to c.toString(); 使用新的String(c)到c.toString();
c.toString() c mean array of chars toString() print hash method c.toString()c表示字符数组toString()打印哈希方法
public class Str3 {
public String frontBack(String str) {
char c[] = str.toCharArray();
char temp = c[0];
c[0] = c[c.length - 1];
c[c.length - 1] = temp;
return new String(c);
}
public static void main(String args[]) {
Str3 s = new Str3();
String s1 = new String("boy");
System.out.println(s1);
String s2 = s.frontBack("boy");
System.out.println(s2);
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.