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

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

当前回答

你可以使用谷歌番石榴表

其他回答

尽管这篇文章现在已经很老了,尽管我知道我真的没有多大帮助,但我认为在向Java添加元组:对轻量级数据结构的研究中描述的建议在主流Java中会很好。

你可以这样做:

int a;
char b;
float c;
[a,b,c] = [3,'a',2.33];

or

[int,int,char] x = [1,2,'a'];

or

public [int,boolean] Find(int i)
{
  int idx = FindInArray(A,i);
  return [idx,idx>=0];
}

[idx, found] = Find(7);

元组如下:

定义为基本类型-没有模板/泛型 如果在本地声明,则为堆栈分配 使用模式匹配进行分配

这种方法增加了

性能 可读性 表达能力

作为@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;
    }
}

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

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

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

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

这里有一个完全相同的问题,其中包括一个更健壮的等号哈希,maerics暗指:

http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/f8b63fc645c1b487/1d94be050cfc249b

这个讨论继续反映了maerics和ColinD的方法,即“每次遇到这种情况时,我应该重用具有非特定名称的类Tuple,还是使用特定名称创建一个新类”。多年前,我属于后者;我已经开始支持前者了。