Java 集合 覆盖ArrayList的toString方法

来源:这里教程网 时间:2026-02-17 20:13:13 作者:

当我们处理对象的ArrayList时,必须覆盖toString()方法以获得所需格式的输出。在本教程中,我们将了解如何在 Java 中覆盖ArrayList的toString()方法。

示例:

我们这里有两个类Student和Demo。Student只有两个属性学生姓名和学生年龄。正如您所看到的,我们已经在Student类本身中重写了toString()方法。在Demo类中,我们将学生对象存储在ArrayList中,然后我们使用高级for循环迭代ArrayList。您可以很好地看到输出采用我们在toString()中指定的格式。您可以根据需要提供toString()编码。

package beginnersbook.com;public class Student {    private String studentname;    private int studentage;    Student(String name, int age)    {         this.studentname=name;         this.studentage=age;    }    @Override    public String toString() {       return "Name is: "+this.studentname+" & Age is: "+this.studentage;    }}

另一个类:

package beginnersbook.com;import java.util.ArrayList;public class Demo{     public static void main(String [] args)     {          ArrayList<Student> al= new ArrayList<Student>();          al.add(new Student("Chaitanya", 26));          al.add(new Student("Ajeet", 25));          al.add(new Student("Steve", 55));          al.add(new Student("Mary", 18));          al.add(new Student("Dawn", 22));          for (Student tmp: al){              System.out.println(tmp);          }     }}

输出:

Name is: Chaitanya & Age is: 26Name is: Ajeet & Age is: 25Name is: Steve & Age is: 55Name is: Mary & Age is: 18Name is: Dawn & Age is: 22

如果我们不会覆盖toString(),我们将得到以下格式的输出:
不覆盖toString()时上述程序的输出

[email protected][email protected][email protected][email protected][email protected]

相关推荐