Implement Pair class in Java
This post will discuss how to implement our own Pair class in Java.
A Pair is a container to store a tuple of two objects. The JDK doesn’t provide any implementation of the Pair class. This might because the Pair class doesn’t specify the relationship between the specified values. Let’s take an example of std::pair
in C++, where its first
and second
fields can be anything. C++ doesn’t indicate what the data pair
class stores. In Java, Map.Entry
is an excellent example with a meaningful name representing a key-value pair.
Despite not having any meaningful relationship between the data stored in the Pair, programmers often miss this functionality in Java. There are workarounds, as discussed here, in detail, to fill the gap. But wouldn’t it be great to implement our own Pair class in Java, which we can customize to our style.
Well, writing a Pair class is actually very simple in Java. Below is a simple custom implementation of the Pair class in Java, which has
- Two public fields –
first
andsecond
, just like in C++. - A private constructor.
- A static factory method
of()
for creating an immutable, TypedPair
instance (that internally calls the private constructor). - Overridden hashCode() and equals() methods to ensure the desired behavior in hash-based collections.
- Overridden
toString()
method to easily print thePair
object.
The following program demonstrates it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; // Pair class class Pair<U, V> { public final U first; // the first field of a pair public final V second; // the second field of a pair // Constructs a new pair with specified values private Pair(U first, V second) { this.first = first; this.second = second; } @Override // Checks specified object is "equal to" the current object or not public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair<?, ?> pair = (Pair<?, ?>) o; // call `equals()` method of the underlying objects if (!first.equals(pair.first)) { return false; } return second.equals(pair.second); } @Override // Computes hash code for an object to support hash tables public int hashCode() { // use hash codes of the underlying objects return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return "(" + first + ", " + second + ")"; } // Factory method for creating a typed Pair immutable instance public static <U, V> Pair <U, V> of(U a, V b) { // calls private constructor return new Pair<>(a, b); } } // Program to implement Pair class in Java class Main { public static void main(String[] args) { Pair<String, Integer> p1 = Pair.of("John", 26); Pair<String, Integer> p2 = Pair.of("Tom", 30); Pair<String, Integer> p3 = Pair.of("John", 26); List<Pair<String, Integer>> pairs = new ArrayList<>(); pairs.add(p1); pairs.add(p2); pairs.add(p3); System.out.println(pairs); Set<Pair<String, Integer>> distinctPairs = new HashSet<>(pairs); System.out.println(distinctPairs); } } |
Output:
[(John, 26), (Tom, 30), (John, 26)]
[(John, 26), (Tom, 30)]
That’s all about Pair class implementation in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)