🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 如何在 Java 中覆盖`ArrayList`的`toString`方法 > 原文: [https://beginnersbook.com/2013/12/how-to-override-tostring-method-for-arraylist-in-java/](https://beginnersbook.com/2013/12/how-to-override-tostring-method-for-arraylist-in-java/) 当我们处理对象的[`ArrayList`](https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/)时,必须覆盖[`toString()`方法](https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#toString())以获得所需格式的输出。在本教程中,我们将了解如何在 Java 中覆盖`ArrayList`的`toString()`方法。 #### 示例: 我们这里有两个类`Student`和`Demo`。`Student`只有两个属性学生姓名和学生年龄。正如您所看到的,我们已经在`Student`类本身中重写了`toString()`方法。在`Demo`类中,我们将学生对象存储在[`ArrayList`](https://beginnersbook.com/2013/12/how-to-initialize-an-arraylist/) 中,然后我们[使用高级`for`循环](https://beginnersbook.com/2013/12/how-to-loop-arraylist-in-java/)迭代`ArrayList`。您可以很好地看到输出采用我们在`toString()`中指定的格式。您可以根据需要提供`toString()`编码。 ```java 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; } } ``` 另一个类: ```java 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); } } } ``` 输出: ```java Name is: Chaitanya & Age is: 26 Name is: Ajeet & Age is: 25 Name is: Steve & Age is: 55 Name is: Mary & Age is: 18 Name is: Dawn & Age is: 22 ``` 如果我们不会覆盖`toString()`,我们将得到以下格式的输出: **不覆盖`toString()`时上述程序的输出**: ```java [email protected] [email protected] [email protected] [email protected] [email protected] ```