Monday, May 3, 2010

TreeSet, TreeMap and Comparator

Comparator provides a compare method to provide total order to TreeSet and TreeMap. Details can be found in http://java.sun.com/javase/6/docs/api/java/util/Comparator.html

When writing compare method, note the following

1. A negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
2. It uses modified mergesort as the underlying sorting mechanism.
3. Keep the compare method simple.
4. Remove, Add, Contain, etc.. method will use Comparator's compare method for comparison. If you compare is wrong, you may end up with logic error when performing remove, add or contain action with TreeSet/TreeMap.

No comments:

Post a Comment

Hadoop - How to setup a Hadoop Cluster

Below is a step-by-step guide which I had used to setup a Hadoop Cluster Scenario 3 VMs involved: 1) NameNode, ResourceManager - Host...