File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes TreeSet & TreeMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "TreeSet & TreeMap" Watch "TreeSet & TreeMap" New topic

TreeSet & TreeMap

Pally Gharmount
Ranch Hand

Joined: Aug 25, 2004
Posts: 34
A question..

if storing your objects in a treemap or treeset. do your objects have to implement comparable interface or compartor interface? whats the difference between these?

i have writtten code that imlements comparable and provides implementation of the compareTo(Object obj) method and works fine.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Both TreeMap and TreeSet maintain a "natural ordering" of elements. This order is determined either by the elements being Comparable or by using a Comparator (which is passed to the Map/Set as a constructor argument).

Comparable elements can be compared to one another using the compareTo(Object o) method.

A Comparator is a "third-party" object that compares two other objects using the method compare(Object o1, Object o2).

See the API for details...




[ April 25, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: TreeSet & TreeMap
jQuery in Action, 3rd edition