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());
我希望输出为 [Jim,Tony]
,如果存在这样的方法,覆盖 ToString
方法的最简单方法是什么?
最佳答案
您实际上需要在您的 Person 类中覆盖 toString() ,它将返回名字,因为 ArrayList 会自动调用封闭类型的 toString 来打印元素的字符串表示形式。
@Override
public String toString() {
return this.firstname;
}
所以,将上面的方法添加到你的 Person 类中,你可能会得到你想要的。
P.S.:- 附带说明,您不需要执行 people.toString()
。只需执行 System.out.println(people)
,它会自动调用 ArrayList
的 toString()
方法。
关于java - 如何覆盖对象的ArrayList的ToString方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13028525/