wood burning stoves*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "TreeSet & TreeMap" Watch "TreeSet & TreeMap" New topic
Author

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
Sheriff

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...

TreeMap:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html

TreeSet:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html

Comparable:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html

Comparator:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html
[ 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
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: TreeSet & TreeMap