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

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


当前回答

简单的方法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");

我能想到的最短的一对是以下,使用Lombok:

@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
    private F first;
    private S second;
}

它拥有@arturh答案的所有好处(除了可比性),它有hashCode, equals, toString和一个静态“构造函数”。

正如许多人已经指出的那样,Pair类是否有用实际上取决于用例。

我认为,对于私有帮助函数,如果使用Pair类可以使代码更具可读性,并且不值得花费精力创建另一个包含所有锅炉代码的值类,那么使用Pair类是完全合法的。

另一方面,如果您的抽象级别要求您清楚地记录包含两个对象或值的类的语义,那么您应该为它编写一个类。如果数据是业务对象,通常就是这种情况。

一如既往,这需要熟练的判断。

对于你的第二个问题,我推荐Apache Commons库中的Pair类。这些可能被认为是Java的扩展标准库:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

你可能还想看看Apache Commons的EqualsBuilder、HashCodeBuilder和ToStringBuilder,它们简化了为业务对象编写值类的过程。

好消息JavaFX有一个键值Pair。

只需添加JavaFX作为依赖项并导入JavaFX .util。对,并像在c++中那样简单地使用。

Pair <Key, Value> 

e.g.

Pair <Integer, Integer> pr = new Pair<Integer, Integer>()

pr.get(key);// will return corresponding value

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