I am studying collections in Java, however, some collections are quite confusing.
According to my understanding, I have prepared the Override chart.Need your help to correct it and understand it properly.
Please correct if wrong.
One more question about
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 ?
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.
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
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.
To summarise, refer the below basics:
hashcode() whenever there is a need to find the object equality
compareTo() for ordering requirements