Override toString() method of ArrayList in Java

When we are working with ArrayList of Objects then it is must that we have to override toString() method of Java ArrayList to get the output in the desired format. Lets learn how to override toString() method.

Lets take an example Employee class, which has two properties empId, empName and their corresponding getters and setters

Employee.java

public class Employee
{
    private int empId;
    private String empName;

    public Employee(int empId, String empName) {
        this.empId = empId;
        this.empName = empName;
    }
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
}

Client.java

In our Client class we will be creating 4 Employee objects and will be adding it to the ArrayList and finally will be printing the list.

import java.util.ArrayList;
import java.util.List;

public class Client {

    public static void main(String[] args) 
    {
        //Creating Employee objects
        Employee e1 = new Employee(1,"Employee1");
        Employee e2 = new Employee(2,"Employee2");
        Employee e3 = new Employee(3,"Employee3");
        Employee e4 = new Employee(4,"Employee4");
        
        //Add all Employee objects to empList
        List<Employee> empList = new ArrayList<Employee>();
        empList.add(e1);
        empList.add(e2);
        empList.add(e3);
        empList.add(e4);
        
        //Print the empList
        System.out.println(empList);
    }
}

Output :

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

The objects hashcode will be printed since we haven’t overriden toString() method. Lets override the toString() method in our Employee class and see what happens

Employee.java

public class Employee
{
    private int empId;
    private String empName;

    public Employee(int empId, String empName) {
        this.empId = empId;
        this.empName = empName;
    }
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    @Override
    public String toString() {
        return "Employee [empId=" + empId + ", empName=" + empName + "]";
    }
}

Now run our Client class again, we will get the the output something like below.

Output

[Employee [empId=1, empName=Employee1], Employee [empId=2, empName=Employee2], Employee [empId=3, empName=Employee3], Employee [empId=4, empName=Employee4]]

Leave a Reply

Your email address will not be published. Required fields are marked *