[英]Printing out an Arraylist
I have an Arraylist here: 我在这里有一个Arraylist:
public static void main(String[] args) {
Person P1 = new Person("Nathen", 144.5, 55.1);
Person P2 = new Person("Jamie", 133, 60);
Person P3 = new Person("Tom", 134, 65);
Person P4 = new Person("Lavi", 170, 70);
ArrayList<String> Person = new ArrayList<String>();{
Person.add(P1.getCategory());
Person.add(P2.getCategory());
Person.add(P3.getCategory());
Person.add(P4.getCategory());
}
System.out.println(Person);
}
How can I get the program to print out the Arraylist
one row at a time instead of the one big row I have now. 我怎样才能使程序一次打印出Arraylist
而不是现在的一大行。
Use for-each loop 使用for-each循环
for(String str : Person){
System.out.println(str);
}
First of all, you should follow the Java naming convention and therefore you should change the variable Person
to person
, or a better name since it's a list of category like categories
. 首先,您应该遵循Java命名约定 ,因此应该将变量Person
更改为person
或更好的名称,因为它是一个类似于category的categories
列表。
Second, coming to your request, a part the loop through each item option, you have 2 others way to print it the person
list out. 其次,来到你的要求,部分是通过每个项目的选择循环,你有2个其他的方式来打印的person
名单了。
You can use the Arrays.toString
method by passing the corresponding array of the person
list. 您可以通过传递person
列表的相应数组来使用Arrays.toString
方法。 This is how you can write it: 这是您如何编写它:
System.out.println(Arrays.toString(person.toArray()));
Output: [Nathen, Jamie, Tom, Lavi]
输出: [Nathen, Jamie, Tom, Lavi]
In case you are using/moved to Java 8+, you can use stream. 如果您要使用/移至Java 8+,则可以使用流。 This is how you can achieve it: 这是实现它的方法:
person.stream().forEach(System.out::println);
Output: 输出:
Nathen Jamie Tom Lavi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.