在自定义ArrayList Java中创建ToString方法
我正在创建自己的arrayList
,并粘在toString()
方法中,您能在打印最后一项后帮助我摆脱逗号吗?
toString()
方法:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(store == null) {
return "[]";
} else {
for (int i = 0; i < size; i++) {
sb.append(store[i].toString() + ", ");
}
return "[" + sb.toString() + "]";
}
}
main
方法:
public static void main(String[] args) {
MyArrayList<String> fruits = new MyArrayList<>();
System.out.println("My array list with fruits :)");
fruits.add("Bananas");
fruits.add("Apples");
fruits.add("Pineapple");
fruits.add("Peaches");
fruits.add("Pears");
fruits.add("Plum");
System.out.println("The list of fruits : " + fruits);
fruits.clear();
System.out.println("All fruits have been eaten =) " + fruits);
输出:
[Bananas, Apples, Pineapple, Peaches, Pears, Plum, ]
I'm creating my own ArrayList
and stuck in the toString()
method, can you help me get rid of the comma after printing the last item?
toString()
method:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(store == null) {
return "[]";
} else {
for (int i = 0; i < size; i++) {
sb.append(store[i].toString() + ", ");
}
return "[" + sb.toString() + "]";
}
}
Main
method:
public static void main(String[] args) {
MyArrayList<String> fruits = new MyArrayList<>();
System.out.println("My array list with fruits :)");
fruits.add("Bananas");
fruits.add("Apples");
fruits.add("Pineapple");
fruits.add("Peaches");
fruits.add("Pears");
fruits.add("Plum");
System.out.println("The list of fruits : " + fruits);
fruits.clear();
System.out.println("All fruits have been eaten =) " + fruits);
Output:
[Bananas, Apples, Pineapple, Peaches, Pears, Plum, ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在字符串开始时插入逗号,然后在索引1开始循环
Concat the comma at the start of the String and start the loop at index 1
只需添加一个条件,仅在索引
i
时仅添加逗号,不等于循环接受的最后一个索引Just add an if condition to only add the comma if the index
i
is not equals to the last index accepted by thefor
loop