Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。
似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。
似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
当前回答
Spring数据有一个Pair,可以像下面这样使用,
Pair<S, T> pair = Pair.of(S type data, T type data)
其他回答
您可以使用谷歌的AutoValue库- https://github.com/google/auto/tree/master/value。
您创建一个非常小的抽象类,并使用@AutoValue注释它,注释处理器为您生成一个具有值语义的具体类。
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;
}
}
在Lombok的新版本中,你可以编译这个可爱的类:
@Value(staticConstructor = "of") public class Pair <E> {
E first, second;
}
并像这样使用它:Pair<Value> pairOfValues = Pair。(value1, value2);
JavaFX(与Java 8捆绑在一起)有Pair< A,B >类
许多人都张贴对代码,可用作地图中的键…如果您试图使用一对作为哈希键(常用习语),请务必查看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>在我的代码的许多部分。有数组、树和其他用于密集和稀疏使用的实现,可以指定您自己的中间映射类。