泛型扩展而不扩展 - 怎么做

Generics extend without extend - how to do

我做了一些事情:

class Tuple1<T1, T2> {
    private T1 a;
    private T2 b;

    public Tuple1(T1 a, T2 b) {
        this.a = a;
        this.b = b;
    }

    public T1 getA() {
        return a;
    }

    public T2 getB() {
        return b;
    }

    @Override
    public String toString() {
        return "[" + a.toString() + ", " + b.toString() + "]";
    }
}

现在要做Tuple2(a,b+c字段)和Tuple3(a,b,c+d字段),功能和Tuple1一样,只是没有extends也没有代码冗余。

你可以创建多个构造函数来做你想做的事情:

例如:

private T1 a;
private T2 b;
//create a new attribute
private T2 c;

//constructor with two attributes
public Tuple1(T1 a, T2 b) {
    this.a = a;
    this.b = b;
}

//constructor with three attributes
public Tuple1(T1 a, T2 b, T2 c) {
    this.a = a;
    this.b = b;
    this.c = c;
}

//getters and setters of your attributes

所以当你想使用两个属性时:

Tuple1 t1 = new Tuple1(a, b);

所以当你想使用三个属性时:

Tuple1 t2 = new Tuple1(a, b, c);

您可以在此 Oracle 教程中了解更多信息:Getting Started

大约 constructors and here

希望对您有所帮助。

你可以为 Tuple3 创建 Tuple2<T1, T2, T3> 和类似的。您可以将 Tuple1<T1, T2> 作为私有字段存储在 Tuple2 中与 T3 c 一起,并实现所有必需的方法,其中一些方法只是将它们的调用委托给适当的 Tuple1 方法。这似乎是多余的,但您确实需要声明一个方法才能调用它,因此无法避免。

您可以考虑以下解决方案:

class Tuple<T1, T2>
{
    private T1 a;
    private T2 b;

    public Tuple1(T1 a, T2 b)
    {
        this.a = a;
        this.b = b;
    }

    public T1 getA() { return a; }

    public T2 getB() { return b; }

    @Override
    public String toString()
    {
        return "[" + a.toString() + ", " + b.toString() + "]";
    }
}

class Tuple2<T1, T2, T3> 
{
    private Tuple1<T1, T2> tuple;
    private T3 c;

    public Tuple2(T1 a, T2 b, T3 c)
    {
        this.tuple = new Tuple1<T1, T2>(a, b);
        this.c = c;
    }

    public T1 getA() { return tuple.getA(); }

    public T2 getB() { return tuple.getB(); }

    public T3 getC() { return c; }

    @Override
    public String toString()
    {
        return "[" + getA().toString() + ", " + getB().toString() + ", " + c.toString() + "]";
    }
}

class Tuple3<T1, T2, T3, T4> 
{
    private Tuple2<T1, T2, T3> tuple;
    private T4 d;

    public Tuple3(T1 a, T2 b, T3 c, T4 d)
    {
        this.tuple = new Tuple2<T1, T2, T3>(a, b, c);
        this.d = d;
    }

    public T1 getA() { return tuple.getA(); }

    public T2 getB() { return tuple.getB(); }

    public T3 getC() { return tuple.getC(); }

    public T4 getD() { return d; }

    @Override
    public String toString()
    {
        return "[" + getA().toString() + ", " + getB().toString() + ", " + getC().toString() + ", " + d.toString() + "]";
    }
}