When we are dealing with ArrayList of Objects then it is must to Override the toString() method in order to get the output in desired format. In this tutorial we will see how to override the toString() method for ArrayList in Java.
Example:
We have two classes here “Student” and “Demo”. Student class has only two properties student name and student age. As you can see that we have overridden the toString() method in Student class itself. In the Demo class we are storing the Student Object in ArrayList and then we iterated the ArrayList using advance for loop. You can very well see that the output is in the format we have specified in toString(). You can give the toString() coding as per your requirement.
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; } }
Another class:
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); } } }
Output:
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
If we wouldn’t have overridden the toString() we would have got the output in below format:
Output of the above programs without overriding toString():
beginnersbook.com.Student@10b28f30 beginnersbook.com.Student@3ad6a0e0 beginnersbook.com.Student@60dbf04d beginnersbook.com.Student@77d80e9 beginnersbook.com.Student@409a44d6
Noso says
Simple to read each and every concept
Peter says
Hi,
I have similar program with same toString method, but my output is with brackets {} and commas.
Ho can I get rid of brackets and commas in the output?
I know it should be overriden by some code like >
String asString = list.toString().replaceAll(“^\\[“, “”).replaceAll(“\\]$”, “”).replace(“,”, “”);
but don’t know how to implement it.
Thanks,
Peter