Skip to content

Instantly share code, notes, and snippets.

@leonelag
Created June 14, 2013 12:45
Show Gist options
  • Save leonelag/5781528 to your computer and use it in GitHub Desktop.
Save leonelag/5781528 to your computer and use it in GitHub Desktop.
Immutable pair of elements. I have used this in many projects, too bad the Java library does not include it by default.
package util;
public class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T,U>> {
private T first;
private U second;
public Pair(T first, U second) {
if (first == null) throw new IllegalArgumentException("First argument must not be null");
if (second == null) throw new IllegalArgumentException("Second argument must not be null");
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first.hashCode();
result = prime * result + second.hashCode();
return result;
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Pair<T,U> other = (Pair<T,U>) obj;
return first.equals(other.first) && second.equals(other.second);
}
@Override
public int compareTo(Pair<T, U> other) {
final int diff = first.compareTo(other.first);
if (diff != 0) return diff;
return second.compareTo(other.second);
}
public static <T extends Comparable<T>, U extends Comparable<U>> Pair<T,U> pair(T first, U second) {
return new Pair<T,U>(first, second);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment