The author says, "When you are creating your own types, be aware that a set needs a way to maintain a storage order, which mean you must implement the Comparable interface and define the ComparableTo method"
The code is appended below.
Questions, 1) What author means here ? 2) When and How the comparaTo method is invoked and used ? 3) In the example, why we need hashCode() and equals() methods? how it is being used ?
It appears that you are reading a book that covers the use of the Java Collections Framework. Since the author advocates the implementation of the Comparable interface, it appears that the author is discussing the use of Collection implementations that maintain object instances in a sorted order. For more information on the Java Collections Framework, please see the Javaranch News Letters. A series of four articles on the Collections Framework appear in the June 2002 through September 2002 issues.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Joined: Dec 31, 2002
Thank You Don,
Look at the code below, why method "public int compareTo(Object o)" never called to compare ?
My understanding is, compareTo will be invoked for the each object I add to the set "a".
Thanks you very much.
Joined: Jul 02, 2002
A HashSet is backed by a HashMap. The objects stored in a HashSet are used as the keys for the HashMap. The values associated with each key in the backing HashMap are just dummy values. Actually, all of the keys share the same dummy value. All of the keys stored in a HashMap must be unique, so the keys of a HashMap are always a set of unique objects.
When a new key/value pair is stored in the backing HashMap, the HashMap.put method will use the equals method of the key to see if the key has already been used. If the key has been used, then the new key/value pair replaces the old key/value pair. The HashMap.put method does not invoke the compareTo method on the key object.