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