如何覆盖对象的 ArrayList 的 ToString 方法? [英] How to override the ToString method of ArrayList of object?

查看:28
本文介绍了如何覆盖对象的 ArrayList 的 ToString 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 方法的最简单方法是什么?

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?

推荐答案

你实际上需要在你的 Person 类中重写 toString(),它会返回 firstname,因为 ArrayList 会自动调用封闭类型的 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.

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

那么,将上面的方法添加到你的 Person 类中,你可能会得到你想要的.

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

P.S.: - 附带说明,您不需要执行 people.toString().只需执行System.out.println(people),它就会自动调用ArrayListtoString()方法.

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.

这篇关于如何覆盖对象的 ArrayList 的 ToString 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆