Which methods are compulsory to override for a collection with custom
Objects as key, value or element ?
There is no compulsion to override the methods of the collection classes. Collection API provides many classes like List
(preserves the order of elements), Set
(eliminates duplicates), Map
(stores elements as key value pairs), etc.. which you can choose and use them directly depending upon your actual use case.
For TreeMap, Is it correct or should we sort by keys only ?
TreepMap sorts the elements by ordering the keys. If you are looking for ordering the elements by value, you can do that in many ways for which you can look here.
Again, there is no compulsion that you need do the ordering of the Map
by key or value, it depends upon your project/business requirement.
UPDATE:
If I want to use hashmap of Customer class, as specified in book its
required to override hashcode and equals methods to work properly.
Yes, for custom classes like Customer
, you need to override equals()
and hashcode()
so that the collection classes know how two Customer
objects are equal. For example, when you are working with Set
, to eliminate duplicates, Set
needs to find how two Customer
objects are equal so that it can preserve only one object.
Also, on the other side, if you want to order the elements (to be stored inside a collection), you need to override compare
from Comparator or compareTo()
from Comparable.
To summarise, refer the below basics:
override equals()
and hashcode()
whenever there is a need to find the object equality
override compare()
or compareTo()
for ordering requirements