Whenever you print any instance of your class, the default
toString
implementation of Object
class is called, which returns the representation that you are getting.
It contains two parts: - Type
and Hashcode
So, in student.Student@82701e that you get as output ->
student.Student
is the Type
, and82701e
is the HashCode
So, you need to override a toString
method in your Student
class to get required String representation
: -
@Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main
class, you print your ArrayList
, it will invoke the toString
method for each instance, that you overrided
rather than the one in Object
class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString
method overrided in Student
class will be invoked and appropriate representation of each instance will be printed.