JAL-2846 changed "Couldn't" to "Could not" in messages.properties
[jalview.git] / src / jalview / datamodel / features / RangeComparator.java
1 package jalview.datamodel.features;
2
3 import jalview.datamodel.ContiguousI;
4
5 import java.util.Comparator;
6
7 /**
8  * A comparator that orders ranges by either start position or end position
9  * ascending. If the position matches, ordering is resolved by end position (or
10  * start position).
11  * 
12  * @author gmcarstairs
13  *
14  */
15 public class RangeComparator implements Comparator<ContiguousI>
16 {
17   public static final Comparator<ContiguousI> BY_START_POSITION = new RangeComparator(
18           true);
19
20   public static final Comparator<ContiguousI> BY_END_POSITION = new RangeComparator(
21           false);
22
23   boolean byStart;
24
25   /**
26    * Constructor
27    * 
28    * @param byStartPosition
29    *          if true, order based on start position, if false by end position
30    */
31   RangeComparator(boolean byStartPosition)
32   {
33     byStart = byStartPosition;
34   }
35
36   @Override
37   public int compare(ContiguousI o1, ContiguousI o2)
38   {
39     int len1 = o1.getEnd() - o1.getBegin();
40     int len2 = o2.getEnd() - o2.getBegin();
41
42     if (byStart)
43     {
44       return compare(o1.getBegin(), o2.getBegin(), len1, len2);
45     }
46     else
47     {
48       return compare(o1.getEnd(), o2.getEnd(), len1, len2);
49     }
50   }
51
52   /**
53    * Compares two ranges for ordering
54    * 
55    * @param pos1
56    *          first range positional ordering criterion
57    * @param pos2
58    *          second range positional ordering criterion
59    * @param len1
60    *          first range length ordering criterion
61    * @param len2
62    *          second range length ordering criterion
63    * @return
64    */
65   public int compare(long pos1, long pos2, int len1, int len2)
66   {
67     int order = Long.compare(pos1, pos2);
68     if (order == 0)
69     {
70       /*
71        * if tied on position order, longer length sorts to left
72        * i.e. the negation of normal ordering by length
73        */
74       order = -Integer.compare(len1, len2);
75     }
76     return order;
77   }
78 }