KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > core > OrderComparator


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.core;
18
19 import java.util.Comparator JavaDoc;
20
21 /**
22  * {@link Comparator} implementation for {@link Ordered} objects,
23  * sorting by order value ascending (resp. by priority descending).
24  *
25  * <p>Non-<code>Ordered</code> objects are treated as greatest order
26  * values, thus ending up at the end of the list, in arbitrary order
27  * (just like same order values of <code>Ordered</code> objects).
28  *
29  * @author Juergen Hoeller
30  * @since 07.04.2003
31  * @see Ordered
32  * @see java.util.Collections#sort(java.util.List, java.util.Comparator)
33  * @see java.util.Arrays#sort(Object[], java.util.Comparator)
34  */

35 public class OrderComparator implements Comparator JavaDoc {
36
37     public int compare(Object JavaDoc o1, Object JavaDoc o2) {
38         int i1 = getOrder(o1);
39         int i2 = getOrder(o2);
40
41         // Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation.
42
return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
43     }
44
45     /**
46      * Determine the order value for the given object.
47      * <p>The default implementation checks against the {@link Ordered}
48      * interface. Can be overridden in subclasses.
49      * @param obj the object to check
50      * @return the order value, or <code>Ordered.LOWEST_PRECEDENCE</code> as fallback
51      */

52     protected int getOrder(Object JavaDoc obj) {
53         return (obj instanceof Ordered ? ((Ordered) obj).getOrder() : Ordered.LOWEST_PRECEDENCE);
54     }
55
56 }
57
Popular Tags