A Generic Pair in Java
Submitted by Jonathan Peterson on March 17, 2009 - 6:41am.
Tagged:
The Java language lacks a tuple type, so when you need to return more than one object from a method call, you need to create a value object to hold the pieces. As noted in a recent Java Posse Podcast, Java has no Pair object in its standard libraries. Here's our implementation of a reusable Pair object, built with Java generics.
Hopefully our code, below, is documented well enough for use as is. But a few points are worth mentioning:
- Nulls are not permitted for either the left or right side of the pair.
- There are no setters for the left and right variables, so this object is immutable. We favor immutability in such objects, as they guarantee threadsafety.
- We use the Jakarta project's Commons Lang package for hash code building. It's surprisingly difficult to write a really good hash function, so we exploit Jakarta's labors here.
-
Pairs are not comparable so as not to require comparability on either side.
Without further ado, Ideograph's generic Pair:
package com.ideograph.lib.util; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; public class Pair<L, R> { private final L left; private final R right; /** * Constructor. Accepts two objects and constructs a pair. *Neither can be null. * * @param left * The left object * @param right * The right object */ public Pair(L left, R right) { Validate.notNull(left); this.left = left; Validate.notNull(right); this.right = right; } /** * Returns the left item of the pair. * * @return the left item */ public L getLeft() { return left; } /** * Returns the right item of the pair. * * @return the left item */ public R getRight() { return right; } /** * Returns true iff the the two pairs are equal. * * @param other * some other pair * @return true if equal */ @Override public boolean equals(Object other) { if (other == this) return true; if (!(other instanceof Pair)) return false; Pair<?, ?> that = (Pair<?, ?>) other; return new EqualsBuilder(). append(this.left, that.left). append(this.right, that.right). isEquals(); } /** * Returns a hash code for this pair * * @return the hash code */ @Override public int hashCode() { return new HashCodeBuilder(). append(this.left). append(this.right). toHashCode(); } /** * Returns the string form of this pair: "(left,right)" */ @Override public String toString() { StringBuilder sb = new StringBuilder("("); sb.append(left.toString()); sb.append(","); sb.append(right.toString()); sb.append(")"); return sb.toString(); } }