Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeSet & TreeMap

 
Pally Gharmount
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic