Implement Triplet class (or a 3-Tuple) in Java

In this post, we will see how to implement our own Triplet class in Java.


 

A Triplet is a container to store a triplet of three objects. Since JDK doesn’t provides any implementation of the Triplet class, some programmers often miss this class in Java. In this post, we will see how to implement our own Triplet class in Java which we can be easily customized to suit our style.

 
Writing a Triplet class is actually very simple in Java. Below is simple implementation of custom Triplet class in Java which has:

  1. Three public fields – first, second and third.
     
  2. A private constructor.
     
  3. Overridden hashCode() and equals() methods to ensure the desired behavior in hash-based collections.
     
  4. Overridden toString() method to print the Triplet instance.
     
  5. Finally, a static factory method of() for creating a Typed and immutable Triplet instance which internally calls the private constructor.

 

Download   Run Code

Output:

[(David, 26, M), (Lisa, 20, F), (David, 26, M)]
[(Lisa, 20, F), (David, 26, M)]

 
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