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

其他回答

Apache Commons Lang 3.0+有几个Pair类: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html

您可以使用javafx实用程序类Pair,它的作用与c++中的Pair <>相同。https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html

这取决于你想用它来做什么。这样做的典型原因是在地图上迭代,为此你可以简单地这样做(Java 5+):

Map<String, Object> map = ... ; // just an example
for (Map.Entry<String, Object> entry : map.entrySet()) {
  System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}

在comp.lang.java的一个线程中。帮助,Hunter Gratzner给出了一些反对在Java中存在Pair结构的论点。主要的论点是类Pair不传递关于两个值之间关系的任何语义(您如何知道“first”和“second”的意思?)

一个更好的实践是为每个应用程序编写一个非常简单的类,就像Mike建议的那样。地图。Entry是一个在名称中包含其含义的对的例子。

总而言之,在我看来,最好有一个类Position(x,y),一个类Range(begin,end)和一个类Entry(key,value),而不是一个通用的Pair(first,second),它不告诉我它应该做什么。

地图。入口界面非常接近c++对。看看具体的实现,比如AbstractMap。SimpleEntry和AbstractMap。SimpleImmutableEntry 第一项是getKey(),第二项是getValue()。