How to override the ToString method of an ArrayList?

class Person { public String firstname; public String lastname; } Person p1 = new Person("Jim","Green"); Person p2 = new Person("Tony","White"); ArrayList<Person> people = new ArrayList<Person>(); people.add(p1); people.add(p2); System.out.println(people.toString()); 

I want the result to be [Jim,Tony] , which is the easiest way to override the ToString method, if such a method exists at all?

+4
source share
4 answers

You really need to override toString () in your Person class, which will return the first name, because the ArrayList automatically calls the toString of the enclosing types to print the string representation of the elements.

 @Override public String toString() { return this.firstname; } 

So, add the above method to your Person class, and you will probably get what you want.

PS : - On a side note, you do not need to do people.toString() . Just execute System.out.println(people) , it will automatically call the toString() method for ArrayList .

+5
source

You can write a static helper method in the Person class:

 public static String toString(ArrayList<Person> people) { Iterator<Person> iter = people.iterator(); .... } 
+2
source

Enter the toString() override method in the Person class.

 public String toString() { return firstname; } 
+2
source

In this case, you must override the toString method of the Person class, since arrayList just iterates over the instance of the Person class.

0
source

Source: https://habr.com/ru/post/1441521/


All Articles