問題:在Java里面使用Pairs或者二元組
在Java里面,我的Hashtable要用到一個元組結構。在Java里面,我可以使用的什么數據結構呢?
Hashtable<Long, Tuple<Set<Long>,Set<Long>>> table = ...
回答一
我不認為在Java中有一個通用的元組類,但是一個自定義的元組就像下面那樣簡單的:
public class Tuple<X, Y> { public final X x; public final Y y; public Tuple(X x, Y y) { this.x = x; this.y = y; }
}
當然,關于如何進一步設計這個類,我們還要保證一些重要的性質,如相等性、不變性等,特別是對于如果你決定使用這個類作為hash的key的話。
回答二
As an extension to @maerics nice answer, I’ve added a few useful methods:
在@maerics答案的基礎上,我添加了一些有用的方法:
public class Tuple<X, Y> { public final X x; public final Y y; public Tuple(X x, Y y) { this.x = x; this.y = y; }@Overridepublic String toString() {return "(" + x + "," + y + ")";}@Overridepublic boolean equals(Object other) {if (other == this) {return true;}if (!(other instanceof Tuple)){return false;}Tuple<X,Y> other_ = (Tuple<X,Y>) other;// this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.return other_.x.equals(this.x) && other_.y.equals(this.y);}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((x == null) ? 0 : x.hashCode());result = prime * result + ((y == null) ? 0 : y.hashCode());return result;}
}
回答三
Apache Commons提供了一些常用的Java工具包括Pair。它實現了Map.Entry, Comparable 和 Serializable.
回答四
下面是一個Comparable元組,補充了@maerics的答案:
import java.util.*;public class ComparableTuple<X extends Comparable<? super X>, Y extends Comparable<? super Y>>extends Tuple<X, Y>implements Comparable<ComparableTuple<X, Y>>
{public ComparableTuple(X x, Y y) {super(x, y);}public int compareTo(ComparableTuple<X, Y> other) {int d = this.x.compareTo(other.x);if (d == 0)return this.y.compareTo(other.y);return d;}
}
文章翻譯自Stack Overflow:https://stackoverflow.com/questions/2670982/using-pairs-or-2-tuples-in-java