指针JAVA错误的变量引用?接收到奇怪的输出,可能是内存地址?
public class working {
public static String str = "123zASdcvb/;[";
public static void main(String[] args){
System.out.println("!!!"+new LetterInventory(str));
}
public static class LetterInventory {
public char[] arr;
public LetterInventory(String str){
//Strips our string of all non alphabetic garbage
//and assigns it. This regex removes all non a-z
//without regard for case of alphabet (?!).
this.arr = str.replaceAll("[^a-z]", "").toLowerCase().toCharArray();
Arrays.sort(this.arr); //I want to have it sorted to make my life easier.
System.out.printf("Our freshly sorted LI is : %s\n",this.toString());
}
//Simple enough.
public String toString() {
return this.arr.toString();
}
}
}
输出:
Our freshly sorted LI is : [C@6d69c9a2
!!![C@6d69c9a2
这里出了什么问题?我浏览了我的调试器,我的数组完全符合我的要求,它被创建、清理和排序都很好。但是每次我试着打印我的字符[]。它出来时有点古怪。为什么会这样
# 1 楼答案
公共字符串toString(){ 返回字符串。copyValueOf(arr); }
如果你得到结果[C@6d69c9a2,这意味着它是一个字符数组([对于数组,c表示字符),其哈希代码为0x6d69c9a2
# 2 楼答案
您正在对数组调用} :
toString()
,因为数组不会覆盖toString()
,所以最终会得到implementation from ^{在处理
char[]
时,应该使用String
构造函数创建一个新字符串:在其他情况下,您可能需要调用
Arrays.toString
重载之一,以获得逗号分隔的表示形式顺便说一句,不清楚你为什么要自己在构造函数中做这些。只要使用
main
方法,您的程序就会更简单: