1   /*
2    *  Copyright (c) 1998-2005, The University of Sheffield.
3    *
4    *  This file is part of GATE (see http://gate.ac.uk/), and is free
5    *  software, licenced under the GNU Library General Public License,
6    *  Version 2, June 1991 (in the distribution as file licence.html,
7    *  and also available at http://gate.ac.uk/gate/licence.html).
8    *
9    *  ObjectComparator.java
10   *
11   *  Valentin Tablan, 06-Dec-2004
12   *
13   *  $Id: ObjectComparator.java,v 1.2 2005/01/11 13:51:37 ian Exp $
14   */
15  
16  package gate.util;
17  
18  import java.util.Comparator;
19  
20  /**
21   * A Comparator implementation for Object values.
22   * If the values provided are not comparable, then they are converted to String 
23   * and the String values are compared.
24   * This utility is useful for GUI components that need to sort their contents.
25   */
26  public class ObjectComparator implements Comparator{
27  
28    /**
29     * Compares two objects.
30     */
31    public int compare(Object o1, Object o2){
32      // If both values are null, return 0.
33      if (o1 == null && o2 == null) {
34        return 0;
35      } else if (o1 == null) { // Define null less than everything.
36        return -1;
37      } else if (o2 == null) {
38        return 1;
39      }
40      int result;
41      if(o1 instanceof Comparable){
42        try {
43          result = ((Comparable)o1).compareTo(o2);
44        } catch(ClassCastException cce) {
45          String s1 = o1.toString();
46          String s2 = o2.toString();
47          result = s1.compareTo(s2);
48        }
49      } else {
50        String s1 = o1.toString();
51        String s2 = o2.toString();
52        result = s1.compareTo(s2);
53      }
54      
55      return result;
56    }
57  }
58