View Javadoc

1   /**
2    * Copyright 2011 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15   
16  package org.kuali.mobility.maps.entity;
17  
18  import java.util.Comparator;
19  
20  public class LocationSort implements Comparator<Location> {
21  
22  	public int compare(Location loc1, Location loc2) {
23  		String cmp1 = loc1.getName();
24  		String cmp2 = loc2.getName();
25  		for (int cmp1pos = 0; cmp1pos < cmp1.length(); cmp1pos++) {
26  			char chr1 = cmp1.charAt(cmp1pos);
27  			if (cmp1pos < cmp2.length()) {
28  				// Still possible to compare at same position
29  				char chr2 = cmp2.charAt(cmp1pos);
30  				boolean chr1IsDigit = Character.isDigit(chr1);
31  				boolean chr2IsDigit = Character.isDigit(chr2);
32  				if (chr1IsDigit && chr2IsDigit) {
33  					// Compare numbers
34  					if (chr1 != chr2) {
35  						return chr1 - chr2;
36  					}
37  				} else if (chr1IsDigit && !chr2IsDigit) {
38  					// chr1 is a number and chr2 is not.
39  					return 1;
40  				} else if (!chr1IsDigit && chr2IsDigit) {
41  					return -1;
42  				} else {
43  					// Compare strings
44  					if (chr1 != chr2) {
45  						return chr1 - chr2;
46  					}
47  				}
48  			} else {
49  				//Our position in cmp1 can no longer be compared to cmp2. loc1 > loc2
50  				return 1;
51  			}
52  		}
53  		if (cmp2.length() > cmp1.length()) {
54  			// cmp2 was able to be compared further but cmp1 ran out of characters. loc2 > loc1
55  			return -1;
56  		}
57  		return 0;
58  	}
59  
60  }