Assume you are writing an application working with Person objects. The application uses Person objects in Collections, placing them into Collection implementations and querying if a Person is in a Collection using the Collection.contains() method. The application also uses Person objects as keys in Maps to associate other objects with Persons and to efficiently look up those objects based on Person. Given these needs, will the following Person implementation work in our application? If not, please fix it so that it will.
It can't work now. Collection.contains(Object o) implementations use o.equals() method to find element in collection. You don't override equals(), so Object.equals() will be used. Two Person objects created with the same constructor arguments will not be equal. You need to override Object.equals() in your class. If you want to use this class as key in map you will also need to override Object.hashCode() to keep equals() and hashCode() contract. Take a look here if you need more information how to implement missing methods: http://bytes.com/topic/java/insights/723476-overriding-equals-hashcode-methods
Joined: Nov 26, 2007
Thanks, that was a very useful explanation of the concept. I have one more doubt. So if we need to sort these Person objects based on the natural ordering of each person’s complete name, then is it ok to just extend Comparator interface and implement the compare() method?
Dorothy Taylor wrote:So if we need to sort these Person objects based on the natural ordering of each person’s complete name, then is it ok to just extend Comparator interface and implement the compare() method?
You cannot extend interface in class, you can implement it. If you tried your idea (which I strongly suggest) then you already noticed it won't work. Not every Map implementation cares about key ordering, you have to choose the one which does (ie. TreeMap).
TreeMap javadoc stands:
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
So you can either implement Comparable (not Comparator) interface in Person class, or create implementation of Comparator and provide it during initialization of map. You would also want to read about Collator if you have to care about national characters in names, like 'é', 'ą', 'ö' etc.