【发布时间】:2020-12-09 19:38:00
【问题描述】:
我正在创建一个具有char[] 数组作为唯一实例变量的类。我必须使用构造函数和访问方法等,但困难的部分是创建一个高效的toString() 方法。
现在,我已将数组初始化为:
private char[] tune = new char[5];
我的 toString() 方法如下所示:
public String toString() {
return notes[0] + " " + notes[1] + " " + notes[2] + " " + notes[3] + " " + notes[4];
}
我的问题是:有没有更有效的打印方法。我想到了用for循环,如下图:
for(int i = 0; i <= tune.length; i++) {
return tune[i] + " ";
}
但我认为这会返回 tune[0] 并停止。
【问题讨论】:
-
这能回答你的问题吗? What's the simplest way to print a Java array?。基本上只是
return Arrays.toString(notes)。 -
在你的第一个 sn-p 中连接元素有什么低效的地方?
-
在循环外创建一个字符串,然后您可以在每次循环迭代的字符串中添加
tune[i] + " "。 -
@takendarkk 的输出会有所不同
-
@eis 我猜你是对的 - 我不确定是否需要 OP 显示的确切输出格式。