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

  1. Two public fields – first and second, just like in C++.
  2. A private constructor.
  3. A static factory method of() for creating an immutable, Typed Pair instance (that internally calls the private constructor).
  4. Overridden hashCode() and equals() methods to ensure the desired behavior in hash-based collections.
  5. Overridden toString() method to easily print the Pair object.

The following program demonstrates it:

Download  Run Code

Output:

[(John, 26), (Tom, 30), (John, 26)]
[(John, 26), (Tom, 30)]

That’s all about Pair class implementation in Java.