01: /* uDig - User Friendly Desktop Internet GIS client
02: * http://udig.refractions.net
03: * (C) 2004, Refractions Research Inc.
04: *
05: * This library is free software; you can redistribute it and/or
06: * modify it under the terms of the GNU Lesser General Public
07: * License as published by the Free Software Foundation;
08: * version 2.1 of the License.
09: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: */
15: package net.refractions.udig.ui;
16:
17: import java.io.Serializable;
18: import java.util.Comparator;
19:
20: import org.eclipse.swt.SWT;
21: import org.geotools.feature.Feature;
22:
23: /**
24: * Sorts features according to their FIDS.
25: *
26: * @author Jesse
27: * @since 1.1.0
28: */
29: public class FIDComparator implements Comparator<Feature>, Serializable {
30:
31: /** long serialVersionUID field */
32: private static final long serialVersionUID = 6541004741916267811L;
33: private int dir;
34:
35: /**
36: * @param dir SWT.UP or SWT.DOWN. If SWT.UP then the largest fids are at the top (sorted top to bottom).
37: */
38: public FIDComparator(int dir) {
39: if (dir == SWT.UP) {
40: this .dir = -1;
41: } else if (dir == SWT.DOWN) {
42: this .dir = 1;
43: } else
44: throw new IllegalArgumentException(
45: "dir must be SWT.UP or SWT.DOWN was: " + dir); //$NON-NLS-1$
46: }
47:
48: public int compare(Feature o1, Feature o2) {
49:
50: String id1 = o1.getID();
51: String id2 = o2.getID();
52:
53: // we're going to try to strip out the same section and see if the remaining is a number
54: // this is so that id.2 will be sorted before id.10
55: // assumption is that the number is at the end... not always a good assumption.
56: int i = 1;
57: while (i < id2.length() && i < id1.length()
58: && id2.regionMatches(0, id1, 0, i)) {
59: i++;
60: }
61: String diff1 = id1.substring(i - 1);
62: String diff2 = id2.substring(i - 1);
63:
64: try {
65: Integer num1 = Integer.valueOf(diff1);
66: Integer num2 = Integer.valueOf(diff2);
67: return dir * num1.compareTo(num2);
68: } catch (NumberFormatException e) {
69: // oh well it was worth a try.
70: }
71: return dir * id1.compareTo(id2);
72: }
73:
74: @Override
75: public int hashCode() {
76: final int PRIME = 31;
77: int result = 1;
78: result = PRIME * result + dir;
79: return result;
80: }
81:
82: @Override
83: public boolean equals(Object obj) {
84: if (this == obj)
85: return true;
86: if (obj == null)
87: return false;
88: if (getClass() != obj.getClass())
89: return false;
90: final FIDComparator other = (FIDComparator) obj;
91: if (dir != other.dir)
92: return false;
93: return true;
94: }
95:
96: }
|