A collection is a set of objects that hold references to other objects in the program. In doing the same we already have studied a data structure- HashMap which internally works out the same way. So we come up with one of the approaches to print a Collection in java that is through HashMap. Now a step further we encounter- collection-framework.
The toString method is inherited by all the Classes in Java in order to print any collection in Java by overriding the toString method. After overriding, we can iterate through the collection using a for-each loop to print all the objects of the collection
Collections in java can be printed through 2 approaches which are:
- Printing a user-defined ArrayList
- Printing a user-defined HashMap
Approach 1: Printing a user-defined ArrayList
Name : John | Roll No : 101 Name : Paul | Roll No : 102 Name : Jack | Roll No : 103 Name : Jose | Roll No : 10
Approach 2: Printing a user-defined HashMap
101 | First Name : Mohit | LastName : Singh 102 | First Name : Tarun | LastName : Anand 103 | First Name : Madhu | LastName : Singh 104 | First Name : Rohit | LastName : Ahuja
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.