本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看 活动链接
问题:在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;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public 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);
}
@Override
public 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:stackoverflow.com/questions/2…
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END