Two Laptop Bag
The moose likes Java in General and the fly likes SET function Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "SET function" Watch "SET function" New topic

SET function

Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
Posts: 139
Hi there,
See the example below.

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.

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 ?

[ June 25, 2004: Message edited by: Siva kandasamy ]
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865

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="" target="_blank" rel="nofollow">Try my mock exam.</a>
Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
Posts: 139
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.

Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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.
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Moving this to the Intermediate forum...

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: SET function
It's not a secret anymore!