How to override the ToString method of ArrayList of object?

帅比萌擦擦* 提交于 2019-12-23 12:24:11

问题


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?


回答1:


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.




回答2:


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

public static String toString(ArrayList<Person> people) {

    Iterator<Person> iter = people.iterator();

    ....


}



回答3:


Write override method toString() method in Person class.

public String toString() {
    return firstname;
}



回答4:


In this case you have to override the toString method of Person class since arrayList just iterates the Person class instance.



来源:https://stackoverflow.com/questions/13028525/how-to-override-the-tostring-method-of-arraylist-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!