JAL-2446 FeatureStore with NCList - work in progress
[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,
8  * 
9  * @author gmcarstairs
10  *
11  */
12 public class RangeComparator implements Comparator<ContiguousI>
13 {
14   boolean byStart;
15
16   @Override
17   public int compare(ContiguousI o1, ContiguousI o2)
18   {
19     int len1 = o1.getEnd() - o1.getBegin();
20     int len2 = o2.getEnd() - o2.getBegin();
21
22     if (byStart)
23     {
24       return compare(o1.getBegin(), o2.getBegin(), len1, len2);
25     }
26     else
27     {
28       return compare(o1.getEnd(), o2.getEnd(), len1, len2);
29     }
30   }
31
32   /**
33    * Compares two ranges for ordering
34    * 
35    * @param pos1
36    *          first range positional ordering criterion
37    * @param pos2
38    *          second range positional ordering criterion
39    * @param len1
40    *          first range length ordering criterion
41    * @param len2
42    *          second range length ordering criterion
43    * @return
44    */
45   public int compare(long pos1, long pos2, int len1, int len2)
46   {
47     int order = Long.compare(pos1, pos2);
48     if (order == 0)
49     {
50       /*
51        * if tied on position order, longer length sorts to left
52        * i.e. the negation of normal ordering by length
53        */
54       order = -Integer.compare(len1, len2);
55     }
56     return order;
57   }
58
59   /**
60    * Constructor
61    * 
62    * @param byStartPosition
63    *          if true, order based on start position, if false by end position
64    */
65   public RangeComparator(boolean byStartPosition)
66   {
67     byStart = byStartPosition;
68   }
69 }