我有一个 toString() 方法。如何让它打印 [A,B,C,D] 而不是 [,A,B,C,D,]
public String toString()
{
String result = "[";
if (numItems > 0)
{
for (int i = 0; i < queueArray.length && queueArray[i] != null; i++)
{
result+= queueArray[i].toString() + ",";
}
result += "]";
}
else
{
result = "[ ]";
}
return result;
}
最佳答案
使用StringJoiner
:
public String toString() {
StringJoiner sj = new StringJoiner(","); // Use commas to attach
if (numItems > 0) {
for (int i = 0; i < queueArray.length && queueArray[i] != null; i++) {
sj.add(queueArray[i].toString()); // Loop through & attach
}
sj.add("]");
} else {
sj.add("[ ]");
}
return sj.toString();
}
这是另一个示例程序,以阐明其工作原理:
public static void main(String[] args) {
// You pass in the "joiner" string into the StringJoiner's constructor
StringJoiner sj = new StringJoiner("/"); // in this case, use slashes
// The strings to be attached
String[] strings = new String[]{"Hello", "World", "!"};
for (String str : strings)
sj.add(str); // Attach
System.out.println(sj.toString()); // Print the content of the StringJoiner
}
输出是:
Hello/World/! // No slash in the end
关于java - 如何不在列表的开头和结尾显示逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078956/