How to create a pair class in Java

A pair class is a very useful programming concept. It supplies a helpful way of managing key to value association.

Pairs are especially helpful when two values are to be returned from a method. For example, there could be a method which computes the square root of a number and returns both the square root and the number itself. Hence, we want to combine a number with its square root. The combination may result in (number, square root of a number), ex., (16,4) and (25,5).

Let’s look at another example of where pairs can be helpful. Imagine there is a list or an array of integers, and we want to create a pair of even numbers from that array.

svg viewer

Types of Pairs:

  • Mutable pair: pairs of data values which can be changed. We can call getter and setter functions on this. We can call functions on this: pair.getValue(); or pair.setValue(1,2).

    Here getValue returns the values stored in the pair, and SetValues sets the values of the pairs.

  • Immutable pair: pair of data values which cannot be changed/set/amended. This means that once the data values are set in the pair,then we cannot call pair.setValue(1,2) ie., no changes allowed.

Example

Simply setting and then getting the values of Pair.

@SuppressWarnings("unchecked") // to prevent warnings.
class main{
public static void main(String args[])
{
Pair<Integer> pair = new Pair<Integer>();
pair.setValue(1,2);
Pair <Integer> answer= new Pair <Integer> ();
answer = pair.getValue();
System.out.println(answer.p1 + " " + answer.p2);
}
}
class Pair<T>
{
T p1, p2;
Pair()
{
//default constructor
}
void setValue(T a, T b)
{
this.p1 = a;
this.p2 = b;
}
Pair getValue()
{
return this;
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved