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

查看:103
本文介绍了如何覆盖对象的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());

我想输出是 [吉姆,托尼] ,什么是覆盖的ToString <最简单的方法/ code>如果法这样的方法存在呢?

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(),这将返回名字,因为,ArrayList中自动调用封闭类型的toString打印字符串重元素的presentation。

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(人),它会自动调用的的toString()方法的ArrayList

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天全站免登陆