In this article, we will discuss and understand why we need to override toString() method for displaying ArrayList contents
Problem statement for ArrayList :
- Assume that we want to store number of Employee records into Collection, preferably ArrayList for faster access
- So, whenever we retrieve Employee records then it must print in certain format
Here, there are 2 cases to be considered to understand the importance of toString() method
1. Provide and implement toString() method in Employee class
- Simply, override toString() method
- Provide/code format details inside toString() method implementation
Let’s start with coding to implement above solution
1.1 Employee class
- Contains four attributes namely Id, name, age, designation
- 4-arg parameterized constructor
- Overrides toString() method providing format detail to print employee information
Employee.java
package in.bench.resources.override.tostring;
public class Employee {
// member variables
private int employeeId;
private String employeeName;
private int employeeAge;
private String employeeDesignation;
// 4-arg parameterized constructor
public Employee(int employeeId, String employeeName,
int employeeAge, String employeeDesignation) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeAge = employeeAge;
this.employeeDesignation = employeeDesignation;
}
// override toString() method
@Override
public String toString() {
return "Employee [employeeId=" + employeeId
+ ", employeeName=" + employeeName
+ ", employeeAge=" + employeeAge
+ ", employeeDesignation=" + employeeDesignation
+ "]";
}
}
1.2 Main class – to store and retrieve employee records
- This class is used to store and retrieve employee records
- ArrayList stores all employee records
- Enhanced forEach loop is used to retrieve employee records
StoreAndRetrieveEmployeeRecords.java
package in.bench.resources.override.tostring;
import java.util.ArrayList;
public class StoreAndRetrieveEmployeeRecords {
public static void main(String[] args) {
// create ArrayList object to store employee records
ArrayList<Employee> empRecords = new ArrayList<Employee>();
// add employee records to AL object
empRecords.add(new Employee(101, "SJ", 19, "Writer"));
empRecords.add(new Employee(102, "RS", 17, "Developer"));
empRecords.add(new Employee(103, "ZR", 25, "Supporter"));
empRecords.add(new Employee(104, "IL", 27, "Manager"));
empRecords.add(new Employee(105, "SR", 15, "Marketer"));
// retrieving employee records using enhanced forEach loop
for(Employee emp : empRecords) {
System.out.println(emp);
}
}
}
Output:
Employee [employeeId=101, employeeName=SJ, employeeAge=19,
employeeDesignation=Writer]
Employee [employeeId=102, employeeName=RS, employeeAge=17,
employeeDesignation=Developer]
Employee [employeeId=103, employeeName=ZR, employeeAge=25,
employeeDesignation=Supporter]
Employee [employeeId=104, employeeName=IL, employeeAge=27,
employeeDesignation=Manager]
Employee [employeeId=105, employeeName=SR, employeeAge=15,
employeeDesignation=Marketer]
2. Going back to our actual question
Q) Why we need to override toString() method for displaying ArrayList contents ?
- In the above example Case 1, we have overridden toString() method
- And also provided implementation detail to print employee information in certain format
- Because of overridden toString() method, we can display employee information in the desired format
- Let’s us move forward and see what would have happened, if we haven’t overridden toString() method
2.1 Employee class
- This is the same employee class, containing 4 attributes namely Id, name, age, designation
- 4-arg parameterized constructor
- But doesn’t override toString() method
- Which means, default toString() method of Object class will get invoked
Employee.java
package in.bench.resources.override.tostring;
public class Employee {
// member variables
private int employeeId;
private String employeeName;
private int employeeAge;
private String employeeDesignation;
// 4-arg parameterized constructor
public Employee(int employeeId, String employeeName,
int employeeAge, String employeeDesignation) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
this.employeeAge = employeeAge;
this.employeeDesignation = employeeDesignation;
}
}
Note: above program doesn’t overrides toString() method
2.2 Main class – to store and retrieve employee records
- This is very same class used in the Case 1
StoreAndRetrieveEmployeeRecords.java
package in.bench.resources.override.tostring;
import java.util.ArrayList;
public class StoreAndRetrieveEmployeeRecords {
public static void main(String[] args) {
// create ArrayList object to store employee records
ArrayList<Employee> empRecords = new ArrayList<Employee>();
// add employee records to AL object
empRecords.add(new Employee(101, "SJ", 19, "Writer"));
empRecords.add(new Employee(102, "RS", 17, "Developer"));
empRecords.add(new Employee(103, "ZR", 25, "Supporter"));
empRecords.add(new Employee(104, "IL", 27, "Manager"));
empRecords.add(new Employee(105, "SR", 15, "Marketer"));
// retrieving employee records using enhanced forEach loop
for(Employee emp : empRecords) {
System.out.println(emp);
}
}
}
Output:
in.bench.resources.override.tostring.Employee@1db9742
in.bench.resources.override.tostring.Employee@106d69c
in.bench.resources.override.tostring.Employee@52e922
in.bench.resources.override.tostring.Employee@25154f
in.bench.resources.override.tostring.Employee@10dea4e
Conclusion:
- Have you noticed, what is getting printed in the output console without toString() method
- It is each employee object representation in hexadecimal format i.e.;
- Qualified_class_name@HashCode_in_HEX_format (i.e.; class-name followed by @ symbol and then hashcode of the Object in hexadecimal format)
- Therefore, it is very necessary to override toString() method to print values of the ArrayList Object in desired format
3. Alternate Way:
One other way, where we can get rid of implementing toString() method to print ArrayList values, is to include getter & setter methods and invoke setter and getter to set & retrieve values accordingly.
Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.
Related Articles:
- Java – String comparison in 3 ways
- Java – String concatenation in 2 ways
- Java – Reverse a String contents in 4 ways
- Java – Split a String contents in 3 ways
- Java – Overriding toString() method to print values of ArrayList
- Java – How to left pad with zeroes to a String ?
- Java – Various ways to iterate through ArrayList
- Java – Various ways to iterate through Vector – 5 ways
- Java – Various ways to iterate through LinkedList – 5 ways
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Happy Coding !!
Happy Learning !!