Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。

似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。


当前回答

HashMap兼容Pair类:

public class Pair<A, B> {
    private A first;
    private B second;

    public Pair(A first, B second) {
        super();
        this.first = first;
        this.second = second;
    }

    public int hashCode() {
        int hashFirst = first != null ? first.hashCode() : 0;
        int hashSecond = second != null ? second.hashCode() : 0;

        return (hashFirst + hashSecond) * hashSecond + hashFirst;
    }

    public boolean equals(Object other) {
        if (other instanceof Pair) {
            Pair otherPair = (Pair) other;
            return 
            ((  this.first == otherPair.first ||
                ( this.first != null && otherPair.first != null &&
                  this.first.equals(otherPair.first))) &&
             (  this.second == otherPair.second ||
                ( this.second != null && otherPair.second != null &&
                  this.second.equals(otherPair.second))) );
        }

        return false;
    }

    public String toString()
    { 
           return "(" + first + ", " + second + ")"; 
    }

    public A getFirst() {
        return first;
    }

    public void setFirst(A first) {
        this.first = first;
    }

    public B getSecond() {
        return second;
    }

    public void setSecond(B second) {
        this.second = second;
    }
}

其他回答

Brian Goetz, Paul Sandoz和Stuart Marks在Devoxx'14的QA环节中解释了原因。

一旦值类型被引入,在标准库中使用泛型对类就会变成技术债。

请参见:Java SE 8是否有对或元组?

试试VAVR元组。

vavr不仅有一组很好的元组类型,而且对函数式编程也有很好的支持。

许多人都张贴对代码,可用作地图中的键…如果您试图使用一对作为哈希键(常用习语),请务必查看Guava的Table<R,C,V>: http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table。对于图边,他们给出了下面的用法示例:

Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
weightedGraph.put(v1, v3, 20);
weightedGraph.put(v2, v3, 5);

weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5

Table将两个键映射到一个值,并单独为这两种类型的键提供有效的查找。我已经开始使用这个数据结构,而不是Map<Pair<K1,K2>, V>在我的代码的许多部分。有数组、树和其他用于密集和稀疏使用的实现,可以指定您自己的中间映射类。

JavaFX(与Java 8捆绑在一起)有Pair< A,B >类

虽然这个问题已经有十多年的历史了,但我觉得有必要提一下,从Java 14开始,Records可以为这个问题提供非常简单和轻量级的解决方案,而不需要任何形式的外部库或依赖项。

例如,以下记录类声明将是实现所需功能所需的全部内容:

record Pair<K, V>(K key, V value) { }

这样一个记录类可以这样使用:

// Declare a pair object containing two integers
var integerIntegerPair = new Pair<>(1, 2);

// Declare a pair object containing a String and an integer
var stringIntegerPair = new Pair<>("String", 20);

// Declare a pair object containing two other pairs!
var pairPairPair = new Pair<>(new Pair<>(1, 2), new Pair<>("String", 20));