Printing out all the objects in array list [duplicate]
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 theType
, and82701e
is theHashCode
So, you need to override a toString
method in your Student
class to get required String representation
: -
@Overridepublic 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 ArrayListSystem.out.println(students); // Or, iterate through it to print each instancefor(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.