Just attempting this question I found in a past exam paper so that I can prepare for an upcoming Java examination.
Provide a generic class Pair for representing pair
The need for a Pair class usually crops up in larger projects - I'm about to (re)implement one for the current project (as previous implementations are not accessible).
Generally I make it an immutable POJO, with a convenience function to create instances. For example:
public class Pair
{
public final T first;
public final U second;
public static Pair of(T first, U second);
}
So that the end-user can write:
return Pair.of (a, b);
and
Pair p = someThing ();
doSomething (p.first);
doSomethingElse (p.second);
As mentioned above, the Pair class should also implement hashCode(), equals(), optional-but-useful toString(), as possibly clone() and compareTo() for use where these are supported by T and U - though extra work is required to describe how these contracts are supported by the Pair class.