Java – print ArrayList element?

How do I print element "e" in ArrayList "list"?

ArrayList<Dog> list = new ArrayList<Dog>();
 Dog e = new Dog();
 list.add(e);
 System.out.println(list);

Solution

Do you want to print the entire list or traverse each element of the list? Either way, printing any meaningful Dog class requires overriding the toString () method from the object class (as described in other answers) to return valid results

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;
        }
    }
}

The output of this code is:

[Tommy,tiger]  
Tommy  
tiger
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>