英文:
printing Arraylist elements one by one
问题
以下是您提供的代码的翻译部分:
有没有人知道如何逐个打印数组中的元素?我有以下代码:
import java.util.ArrayList;
import java.util.Iterator;
public class SimpleCollection {
private String name;
private ArrayList<String> elements;
public SimpleCollection(String name) {
this.name = name;
this.elements = new ArrayList<>();
}
public void add(String element) {
this.elements.add(element);
}
public ArrayList<String> getElements() {
return this.elements;
}
public String toString(){
String printOutput = "集合" + this.name + "有" + elements.size() + "个元素:";
String e = "";
if(elements.isEmpty()){
return(printOutput + "为空。");
}if(elements.size()==1){
return "集合" + this.name + "有" + elements.size() + "个元素:" + "\n" + elements.get(0) + "\n";
}
e = printOutput + "\n" + getElements() + "\n";
return e;
}
}
我写的toString方法将元素打印为数组:我如何逐个打印它们?类似于:
集合characters有3个元素:
magneto
mystique
phoenix
请注意,代码中的HTML实体(例如<
和>
)已被正确地翻译为普通的尖括号。
英文:
Does anyone here know how to print elements from the array one by one? I have this code here:
import java.util.ArrayList;
import java.util.Iterator;
public class SimpleCollection {
private String name;
private ArrayList<String> elements;
public SimpleCollection(String name) {
this.name = name;
this.elements = new ArrayList<>();
}
public void add(String element) {
this.elements.add(element);
}
public ArrayList<String> getElements() {
return this.elements;
}
public String toString(){
String printOutput = "The collection "+ this.name+ " has "+ elements.size()+ " elements: ";
String e = "";
if(elements.isEmpty()){
return(printOutput+ " is empty.");
}if(elements.size()==1){
return "The collection "+ this.name+ " has "+ elements.size()+" element:"+ "\n"+ elements.get(0)+ "\n";
}
e = printOutput + "\n"+ getElements() + "\n";
return e;
}
}
The toString method of mine prints elements as an array: how can i print them one by one? Something like:
The collection characters has 3 elements:
magneto
mystique
phoenix
答案1
得分: 0
为了以你提供的示例方式获取输出(magneto mystique phoenix
),一个快速的方法是:
String.join(" ", getElements())
希望有所帮助。
英文:
To get an output in the way you gave for an example (magneto mystique phoenix
) one quick way would be
String.join(" ", getElements())
HTH
专注分享java语言的经验与见解,让所有开发者获益!
评论