home *** CD-ROM | disk | FTP | other *** search
/ Java Programmer's Toolkit / Java Programmer's Toolkit.iso / applets / collectn / defaultc.jav < prev    next >
Encoding:
Text File  |  1995-10-14  |  1.9 KB  |  70 lines

  1. /*
  2.   File: DefaultComparator.java
  3.  
  4.   Originally written by Doug Lea and released into the public domain. 
  5.   Thanks for the assistance and support of Sun Microsystems Labs, Agorics 
  6.   Inc, Loral, and everyone contributing, testing, and using this code.
  7.  
  8.   History:
  9.   Date     Who                What
  10.   24Sep95  dl@cs.oswego.edu   Create from collections.java  working file
  11.  
  12. */
  13.   
  14. package collections;
  15.  
  16. import java.util.Enumeration;
  17. import java.util.NoSuchElementException;
  18.  
  19. /**
  20.  *
  21.  *
  22.  * DefaultComparator provides a general-purpose but slow compare
  23.  * operation. 
  24.  * @author Doug Lea
  25.  * @version 0.93
  26.  *
  27.  * <P> For an introduction to this package see <A HREF="index.html"> Overview </A>.
  28. **/
  29.  
  30. public class DefaultComparator implements Comparator {
  31.  
  32. /** 
  33.  * Try various downcasts to find a basis for
  34.  * comparing two elements. If all else fails, just compare
  35.  * hashCodes(). This can be effective when you are
  36.  * using an ordered implementation data structure like trees,
  37.  * but don't really care about ordering.
  38.  *
  39.  * @param fst first argument
  40.  * @param snd second argument
  41.  * @return a negative number if fst is less than snd; a
  42.  * positive number if fst is greater than snd; else 0
  43. **/
  44.  
  45.  
  46.   public int compare(Object fst, Object snd) {
  47.  
  48.     Object a = fst;
  49.     Object b = snd;
  50.     if (fst instanceof Keyed)  a = ((Keyed)(fst)).key();
  51.     if (snd instanceof Keyed)  b = ((Keyed)(snd)).key();
  52.     if (a == b)
  53.       return 0;
  54.     else if ((a instanceof String) && (b instanceof String)) {
  55.       return ((String)(a)).compareTo((String)(b));
  56.     }
  57.     else if ((a instanceof Number) && (b instanceof Number)) {
  58.       double diff = ((Number)(a)).doubleValue() - 
  59.         ((Number)(b)).doubleValue();
  60.       if (diff < 0.0) return -1; 
  61.       else if (diff > 0.0) return 1; 
  62.       else return 0;
  63.     }
  64.     else if (a.equals(b))
  65.       return 0;
  66.     else 
  67.       return a.hashCode() - b.hashCode();
  68.   }
  69. }
  70.