Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override the ToString method of ArrayList of object?

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'd like the output to be [Jim,Tony], what is the simplest way to override the ToString method if such a method exists at all?

like image 440
Terry Li Avatar asked Jan 15 '23 06:01

Terry Li


1 Answers

You actually need to override toString() in your Person class, which will return the firstname, because, ArrayList automatically invokes the toString of the enclosing types to print string representation of elements.

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

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

P.S.: - On a side note, you don't need to do people.toString(). Just do System.out.println(people), it will automatically invoke the toString() method for ArrayList.

like image 164
Rohit Jain Avatar answered Jan 31 '23 01:01

Rohit Jain