Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。
似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
Java中没有Pair<L,R>,有什么好理由吗?与这个c++构造等价的是什么?我宁愿避免重新实现我自己的。
似乎1.6提供了类似的东西(AbstractMap.SimpleEntry<K,V>),但这看起来相当复杂。
当前回答
我能想到的最短的一对是以下,使用Lombok:
@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
private F first;
private S second;
}
它拥有@arturh答案的所有好处(除了可比性),它有hashCode, equals, toString和一个静态“构造函数”。
其他回答
我能想到的最短的一对是以下,使用Lombok:
@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
private F first;
private S second;
}
它拥有@arturh答案的所有好处(除了可比性),它有hashCode, equals, toString和一个静态“构造函数”。
Apache Commons Lang 3.0+有几个Pair类: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html
简单的方法Object[] -可以作为一个几何体元组使用
根据Java语言的性质,我认为人们实际上并不需要Pair,通常他们需要的是一个接口。这里有一个例子:
interface Pair<L, R> {
public L getL();
public R getR();
}
所以,当人们想要返回两个值时,他们可以这样做:
... //Calcuate the return value
final Integer v1 = result1;
final String v2 = result2;
return new Pair<Integer, String>(){
Integer getL(){ return v1; }
String getR(){ return v2; }
}
This is a pretty lightweight solution, and it answers the question "What is the semantic of a Pair<L,R>?". The answer is, this is an interface build with two (may be different) types, and it has methods to return each of them. It is up to you to add further semantic to it. For example, if you are using Position and REALLY want to indicate it in you code, you can define PositionX and PositionY that contains Integer, to make up a Pair<PositionX,PositionY>. If JSR 308 is available, you may also use Pair<@PositionX Integer, @PositionY Ingeger> to simplify that.
编辑: 这里我应该指出的一点是,上面的定义显式地将类型参数名和方法名联系起来。这是对那些认为Pair缺乏语义信息的人的回答。实际上,getL方法的意思是“给我对应于类型参数L的类型的元素”,这确实意味着什么。
编辑: 下面是一个简单的实用程序类,可以让生活变得更简单:
class Pairs {
static <L,R> Pair<L,R> makePair(final L l, final R r){
return new Pair<L,R>(){
public L getL() { return l; }
public R getR() { return r; }
};
}
}
用法:
return Pairs.makePair(new Integer(100), "123");
Spring数据有一个Pair,可以像下面这样使用,
Pair<S, T> pair = Pair.of(S type data, T type data)