This post will discuss 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 implement the Triplet class, some programmers often miss this class in Java. This post will discuss how to implement our own Triplet class in Java, which can be easily customized to suit our style.

 
Writing a Triplet class is actually very simple in Java. Following is a simple implementation of the custom Triplet class in Java, which has the following fields and methods:

  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.

The following program demonstrates it:

Download  Run Code

Output:

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

That’s all about Triplet class implementation in Java.