swapyonubuntu swapyonubuntu - 12 days ago 6
Java Question

Which methods must be ideally overriden for a collection of custom object eg: Customer?

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.

Collections table
Please correct if wrong.

One more question about

TreeMap
.
I read about
TreeMap
, it sorts elements by KEYS using natural or custom order specified by
Comparator
. However, in some tutorials, it is specified that it can be sorted by values instead of keys. Is it correct or should we sort by keys only?

Update :
Sorry if my question feels bit ambiguous.
I am assuming I am putting my custom object of type Customer(java class) in each collection.
In key value pair collections, I am using Customer as key.

Answer

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

Comments