1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.core;
18
19 import org.junit.Assert;
20 import org.junit.Test;
21
22
23
24
25 public class PairTest {
26
27 @Test
28 public void testAccessor() {
29 final Pair<Integer, Double> p
30 = new Pair<>(Integer.valueOf(1), Double.valueOf(2));
31 Assert.assertEquals(Integer.valueOf(1), p.getKey());
32 Assert.assertEquals(2, p.getValue().doubleValue(), Math.ulp(1d));
33 }
34
35 @Test
36 public void testAccessor2() {
37 final Pair<Integer, Double> p
38 = new Pair<>(Integer.valueOf(1), Double.valueOf(2));
39
40
41
42 Assert.assertSame(p.getFirst(), p.getKey());
43 Assert.assertSame(p.getSecond(), p.getValue());
44 }
45
46 @Test
47 public void testEquals() {
48 Pair<Integer, Double> p1 = new Pair<>(null, null);
49 Assert.assertNotEquals(p1, null);
50
51 Pair<Integer, Double> p2 = new Pair<>(null, null);
52 Assert.assertEquals(p1, p2);
53
54 p1 = new Pair<>(Integer.valueOf(1), Double.valueOf(2));
55 Assert.assertNotEquals(p1, p2);
56
57 p2 = new Pair<>(Integer.valueOf(1), Double.valueOf(2));
58 Assert.assertEquals(p1, p2);
59
60 Pair<Integer, Float> p3 = new Pair<>(Integer.valueOf(1), Float.valueOf(2));
61 Assert.assertNotEquals(p1, p3);
62 }
63
64 @Test
65 public void testHashCode() {
66 final MyInteger m1 = new MyInteger(1);
67 final MyInteger m2 = new MyInteger(1);
68
69 final Pair<MyInteger, MyInteger> p1 = new Pair<>(m1, m1);
70 final Pair<MyInteger, MyInteger> p2 = new Pair<>(m2, m2);
71
72 Assert.assertEquals(p1.hashCode(), p2.hashCode());
73
74
75 m2.set(2);
76 Assert.assertNotEquals(p1.hashCode(), p2.hashCode());
77 }
78
79 @Test
80 public void testToString() {
81 Assert.assertEquals("[null, null]", new Pair<>(null, null).toString());
82 Assert.assertEquals("[foo, 3]", new Pair<>("foo", 3).toString());
83 }
84
85 @Test
86 public void testCreate() {
87 final Pair<String, Integer> p1 = Pair.create("foo", 3);
88 Assert.assertNotNull(p1);
89 final Pair<String, Integer> p2 = new Pair<>("foo", 3);
90 Assert.assertEquals(p2, p1);
91 }
92
93
94
95
96 private static class MyInteger {
97 private int i;
98
99 MyInteger(int i) {
100 this.i = i;
101 }
102
103 public void set(int value) {
104 this.i = value;
105 }
106
107 @Override
108 public boolean equals(Object o) {
109 if (!(o instanceof MyInteger)) {
110 return false;
111 } else {
112 return i == ((MyInteger) o).i;
113 }
114 }
115
116 @Override
117 public int hashCode() {
118 return i;
119 }
120 }
121 }