简体   繁体   English

如何覆盖对象的ArrayList的ToString方法?

[英]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? 我希望输出为[Jim,Tony] ,如果存在这样的方法,那么覆盖ToString方法的最简单方法是什么?

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. 实际上你需要覆盖Person类中的toString(),它将返回firstname,因为,ArrayList会自动调用封闭类型的toString来打印元素的字符串表示。

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

So, add the above method to your Person class, and probably you will get what you want. 所以,将上面的方法添加到Person类中,可能你会得到你想要的。

PS : - On a side note, you don't need to do people.toString() . PS : - 在旁注中,您不需要执行people.toString() Just do System.out.println(people) , it will automatically invoke the toString() method for ArrayList . 只需执行System.out.println(people) ,它就会自动为ArrayList调用toString()方法。

You can write a static helper method on the Person class: 您可以在Person类上编写静态帮助器方法:

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

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

    ....


}

Write override method toString() method in Person class. Person类中写入覆盖方法toString()方法。

public String toString() {
    return firstname;
}

在这种情况下,您必须覆盖Person类的toString方法,因为arrayList只是迭代Person类实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM