View Javadoc

1   /*
2    * Copyright 2005-2008 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  package org.springframework.ldap.support;
17  
18  import java.io.Serializable;
19  import java.util.Comparator;
20  import java.util.List;
21  
22  /**
23   * Comparator for comparing lists of Comparable objects.
24   * 
25   * @author Mattias Hellborg Arthursson
26   */
27  public class ListComparator implements Comparator, Serializable {
28  	private static final long serialVersionUID = -3068381879731157178L;
29  
30  	/**
31  	 * Compare two lists of Comparable objects.
32  	 * 
33  	 * @param o1 the first object to be compared.
34  	 * @param o2 the second object to be compared.
35  	 * @throws ClassCastException if any of the lists contains an object that
36  	 * is not Comparable.
37  	 */
38  	public int compare(Object o1, Object o2) {
39  		List list1 = (List) o1;
40  		List list2 = (List) o2;
41  
42  		for (int i = 0; i < list1.size(); i++) {
43  			if (list2.size() > i) {
44  				Comparable component1 = (Comparable) list1.get(i);
45  				Comparable component2 = (Comparable) list2.get(i);
46  				int componentsCompared = component1.compareTo(component2);
47  				if (componentsCompared != 0) {
48  					return componentsCompared;
49  				}
50  			}
51  			else {
52  				// First instance has more components, so that instance is
53  				// greater.
54  				return 1;
55  			}
56  		}
57  
58  		// All components so far are equal - if the other instance has
59  		// more components it is greater otherwise they are equal.
60  		if (list2.size() > list1.size()) {
61  			return -1;
62  		}
63  		else {
64  			return 0;
65  		}
66  	}
67  }