Printing TreeMap Having Custom Class Objects as Keys or Values in Java
TreeMap is a map implementation that keeps its entry sorted according to the natural ordering of its keys. So, for an integer, this would mean ascending order, and for string, it would be alphabetical order. TreeMap can also be sorted according to the user by using a comparator at construction time.
Here we are going to see how to print TreeMap having custom class objects as keys or values. But before that, let’s see exactly what happens when trying to print it normally. While trying to print object directly printed value might not be in proper format and in multiple cases garbage values like @agc1243 print at the output.
Normal Printing implementation:
1=>Student@3941a79c 2=>Student@506e1b77 3=>Student@4fca772d
The reason why the output is not in the proper format?
The reason is our Student class has not overridden the toString method from the Object class. So that is why the toString method of the Object class is used here which prints “class_name@object_hashcode” when an object is printed.
So, the next question is How to fix this?
To fix this, override the toString method in our Student class.
1=>[101=>Abhay] 2=>[102=>Sarika] 3=>[103=>Vanshika]
Note: So the main tip here to remember is to always override the toString() method in your custom classes.
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.