KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > cache > FqnComparator


1 /*
2  * JBoss, Home of Professional Open Source
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.cache;
8
9 import java.util.Comparator JavaDoc;
10
11 /**
12  * Compares the order of two FQN.
13  * Sorts by name, then by depth, e.g.
14  * <pre>
15  * aaa/bbb
16  * xxx
17  * xxx/ccc
18  * </pre>
19  *
20  * @author Manik Surtani (<a HREF="mailto:manik@jboss.org">manik@jboss.org</a>)
21  * @author Steve Woodcock (<a HREF="mailto:stevew@jofti.com">stevew@jofti.com</a>)
22  */

23 public class FqnComparator implements Comparator JavaDoc<Fqn>
24 {
25    public static final FqnComparator INSTANCE = new FqnComparator();
26
27    /**
28     * Sorts by name, then depth.
29     */

30    public FqnComparator()
31    {
32    }
33
34    /**
35     * Returns -1 if the first comes before; 0 if they are the same; 1 if the
36     * second Fqn comes before. <code>null</code> always comes first.
37     */

38    public int compare(Fqn fqn1, Fqn fqn2)
39    {
40       int s1 = fqn1.size();
41       int s2 = fqn2.size();
42
43       if (s1 == 0)
44       {
45          return (s2 == 0) ? 0 : -1;
46       }
47
48       if (s2 == 0)
49       {
50          return 1;
51       }
52
53       int size = Math.min(s1, s2);
54
55       for (int i = 0; i < size; i++)
56       {
57          Object JavaDoc e1 = fqn1.get(i);
58          Object JavaDoc e2 = fqn2.get(i);
59          if (e1 == e2)
60             continue;
61          if (e1 == null)
62             return 0;
63          if (e2 == null)
64             return 1;
65          if (!e1.equals(e2))
66          {
67             int c = compareElements(e1, e2);
68             if (c != 0)
69                return c;
70          }
71       }
72
73       return s1 - s2;
74    }
75
76    /**
77     * Compares two Fqn elements.
78     * If e1 and e2 are the same class and e1 implements Comparable,
79     * returns e1.compareTo(e2).
80     * Otherwise, returns e1.toString().compareTo(e2.toString()).
81     */

82    private int compareElements(Object JavaDoc e1, Object JavaDoc e2)
83    {
84       if (e1.getClass() == e2.getClass() && e1 instanceof Comparable JavaDoc)
85       {
86          return ((Comparable JavaDoc) e1).compareTo(e2);
87       }
88       else
89       {
90          return e1.toString().compareTo(e2.toString());
91       }
92    }
93
94
95 }
96
Popular Tags