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