我的Java哈希表将受益于具有元组结构的值。我可以在Java中使用什么数据结构来做到这一点?

Hashtable<Long, Tuple<Set<Long>,Set<Long>>> table = ...

当前回答

你可以使用谷歌番石榴表

其他回答

Apache Commons提供了一些常见的java实用程序,包括Pair。它实现了Map。条目,可比较和序列化。

javatuples是Java中专门用于元组的项目。

Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)

另外2美分:从Java 7开始,现在在标准Lib中有一个类:javafx.util.Pair。

是的,它是标准Java,现在JavaFx包含在JDK中:)

作为@maerics nice answer的扩展,我添加了一些有用的方法:

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;
    }
}

你可以使用谷歌番石榴表