我如何在arraylist“list”中打印元素“e”?
ArrayList<Dog> list = new ArrayList<Dog>(); Dog e = new Dog(); list.add(e); System.out.println(list);
解决方法
要打印整个列表还是要遍历列表的每个元素?无论哪种方式打印任何有意义的Dog类需要从Object类覆盖toString()方法(如其他答案中所述),以返回有效的结果.
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