我该如何在java中编写这个类?

时间:2015-08-23 13:45:06

标签: java

我想写一个类对,就像这样:

class Pair{
    Integer a , b;
    public Pair(Integer a, Integer b){
       this.a = a;
       this.b = b;
    }
}

现在我想编写一个返回类型为Pair<Integer,Pair>的函数。 如何在不另外上课的情况下写这个?正如我所尝试的那样,它给出了错误,因为类Pair中的第二个参数是int,而在方法中它是Pair

3 个答案:

答案 0 :(得分:3)

您可以使用泛型

class Pair<L, R>{
    L l ;
    R r;
    private Pair(L l, R r){
       this.l = l;
       this.r = r;
    }
    public static <L, R> Pair<L, R> of(L l, R r) {
       return new Pair<>(l, r);
    }
}

所以你可以写

Pair<Integer, Integer> ints = Pair.of(1, 2);
Pair<Integer, Pair<Integer, Integer>> mixed = Pair.of(3, ints);

答案 1 :(得分:2)

使用Apache Commons Lang它有一个Pair

答案 2 :(得分:2)

您需要阅读generics,但基本上我会考虑修改您的Pair课程,如下所示:

class Pair<A,B> {
    A a;
    B b;

    public Pair(A a, B b){
        this.a = a;
        this.b = b;
    }

    public static void main(String[] args) {
        Pair<Integer,Pair<Integer, Integer>> pairpair = new Pair(1, new Pair(2, 3));
    }
}
相关问题