Implement Pair class in Java

In this post, we will see 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 provides any implementation of the Pair class. This might be 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 indicates what the data pair class stores. In Java, Map.Entry is an excellent example that has a meaningful name which represent 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 simple custom implementation of 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 a 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.

 

Download   Run Code

Output:

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz