打印arraylist元素? [英] print arraylist element?
本文介绍了打印arraylist元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在arraylistlist中打印元素e?
how do i print the element "e" in arraylist "list" out?
ArrayList<Dog> list = new ArrayList<Dog>();
Dog e = new Dog();
list.add(e);
System.out.println(list);
推荐答案
是否要打印整个列表或者你想要的迭代列表中的每个元素?无论哪种方式打印任何有意义的 Dog
类都需要覆盖 toString()
方法(如其他答案中所述)从 Object
类返回有效结果。
Do you want to print the entire list or you want to iterate through each element of the list? Either way to print anything meaningful your Dog
class need to override the toString()
method (as mentioned in other answers) from the Object
class to return a valid result.
public class Print {
public static void main(final String[] args) {
List<Dog> list = new ArrayList<Dog>();
Dog e = new Dog("Tommy");
list.add(e);
list.add(new Dog("tiger"));
System.out.println(list);
for(Dog d:list) {
System.out.println(d);
// prints [Tommy, tiger]
}
}
private static class Dog {
private final String name;
public Dog(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
此代码的输出是:
[Tommy, tiger]
Tommy
tiger
这篇关于打印arraylist元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文