在Java中没有Pair<L,R>有一个很好的理由吗?这个C++结构的等效性是什么?我宁愿避免重新实施我自己的。
1.6似乎提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
发布于 2008-10-01 08:18:24
在comp.lang.java.help中,Hunter给出了反对Pair构造在Java中存在的一些论点。主要的论点是,类Pair并不表示关于两个值之间关系的任何语义(您如何知道“第一”和“第二”是什么意思?)
一个更好的实践是为每个应用程序编写一个非常简单的类,就像Mike建议的那样,每个应用程序都会使用Pair类。Map.Entry是一对以其名称表示其含义的对的一个例子。
总之,在我看来,最好有一个类Position(x,y)、一个类Range(begin,end)和一个类Entry(key,value),而不是一个不告诉我它应该做什么的通用Pair(first,second)。
发布于 2010-02-27 10:41:54
这是爪哇。您必须使用描述性类名和字段名来定制自己的对对类,而不必担心您将通过编写hashCode()/equals()或一次又一次地实现可比较性来重新发明轮子。
发布于 2009-03-24 12:55:19
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;
}
}https://stackoverflow.com/questions/156275
复制相似问题