top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How do you use a custom object as key in collection classes like HashMap?

0 votes
324 views
How do you use a custom object as key in collection classes like HashMap?
posted Nov 18, 2017 by Gn Guruswamy

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

–1 vote

If one is using the custom object as key then one needs to override equals() and hashCode() method, and one also need to fulfill the contract. If you want to store the custom object in the SortedCollections like SortedMap then one needs to make sure that equals() method is consistent to the compareTo() method. If inconsistent , then collection will not follow their contracts ,that is , Sets may allow duplicate elements.

answer Nov 19, 2017 by Frank Lee
...