问题

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

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


#1 热门回答(359 赞)

comp.lang.java.help中的一个线程中,Hunter Gratzner给出了一些反对在Java中存在Pair结构的论据。主要论点是类“Pair”没有传达关于两个值之间关系的任何语义(你怎么知道“第一”和“第二”是什么意思?)。

更好的做法是编写一个非常简单的类,就像迈克提出的那样,为每个应用程序编写Pair类。 Map.Entry是一个在其名称中带有其含义的对的示例。

总而言之,在我看来,最好有一个类Position(x,y),一个类Range(开始,结束)和一个类Entry(key,value)而不是一个通用的Pair (第一,第二)它没有告诉我它应该做什么。


#2 热门回答(135 赞)

这是Java。你必须使用描述性的类和字段名称来创建自己的Pair类,并且不要介意通过编写hashCode()/ equals()或一次又一次地实现Comparable来重新发明轮子。


#3 热门回答(99 赞)

HashMap兼容对类:

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

原文链接