带有 toCharArray() 的字符串文字在 Java 中产生垃圾

String literal with toCharArray() producing garbage in Java

我想创建一个字符数组。我看了这个 post:

Better way to generate array of all letters in the alphabet

这是这样说的:

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

所以在我的代码中我有:

public class Alphabet {

private char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

public String availableLetters(){

    return letters.toString();
   } 

}

当我从 main() 调用函数 availableLetters() 并将其打印到控制台时,它输出了这个垃圾:

[C@15db9742

我做错了什么?

数组是正确的,问题是你没有正确打印它。

如果一次打印一个字符的数组,您会得到正确的结果:

for (char c : letters) {
    System.out.print("'" + c + "' ");
}

demo

不幸的是,Java 标准 class 库没有为数组提供有意义的 toString() 覆盖,给刚接触该语言的程序员带来很多麻烦。

如果要以数组形式打印,则使用:

System.out.println(Arrays.toString(letters));

顺便说一句[C@15db9742 并不是真正的垃圾。这是当 class 没有覆盖 toString() 方法时打印出来的内容。

来自Object.toString()

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. 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())

您可以将 char 数组传递给 String 构造函数或静态方法 String.valueOf() 和 return。