JAL-3878 Add action and task for annotation services
[jalview.git] / src / jalview / util / Pair.java
1 package jalview.util;
2
3 import java.util.Iterator;
4 import java.util.List;
5 import java.util.Objects;
6
7 /**
8  * A generic immutable pair of values.
9  * 
10  * @author mmwarowny
11  *
12  * @param <T>
13  *          first value type
14  * @param <U>
15  *          second value type
16  */
17 public class Pair<T, U> implements Iterable<Object>
18 {
19   final T val0;
20
21   final U val1;
22
23   public Pair(T val0, U val1)
24   {
25     this.val0 = val0;
26     this.val1 = val1;
27   }
28   
29   /**
30    * Return value at the specified index cast to type R
31    * @param <R> return type
32    * @param index item index
33    * @return value at given index
34    * @throws ClassCastException value cannot be cast to R
35    * @throws IndexOutOfBoundsException index outside tuple size
36    */
37   @SuppressWarnings("unchecked")
38   public <R> R get(int index) throws ClassCastException, IndexOutOfBoundsException
39   {
40     if (index == 0)
41       return (R) val0;
42     if (index == 1)
43       return (R) val1;
44     throw new IndexOutOfBoundsException(index);
45   }
46
47   /**
48    * @return 0th value of the pair
49    */
50   public T get0()
51   {
52     return val0;
53   }
54
55   /**
56    * @return 1st value of the pair
57    */
58   public U get1()
59   {
60     return val1;
61   }
62   
63   /**
64    * @return tuple size
65    */
66   public int size()
67   {
68     return 2;
69   }
70
71   @Override
72   public boolean equals(Object obj)
73   {
74     if (obj instanceof Pair)
75     {
76       Pair<?, ?> other = (Pair<?, ?>) obj;
77       return Objects.equals(val0, other.val0) &&
78           Objects.equals(val1, other.val1);
79     }
80     return false;
81   }
82
83   @Override
84   public Iterator<Object> iterator()
85   {
86     return List.of(val0, val1).iterator();
87   }
88 }