2017-01-26 71 views
2

我已經做了一些東西:泛型延伸,而不擴展 - 怎麼辦

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且沒有代碼冗餘。

+1

有趣的家庭作業。任何想法如何解決它? – GhostCat

+0

您當前的使用情況沒有擴展。你認爲代碼冗餘是什麼意思 - 在Tuple2的構造中重用Tuple1? – ucsunil

+0

你可以看一下jOOλ庫的源代碼,它實現了非常類似於你想要做的事情:http://www.jooq.org/products/jOO%CE%BB/javadoc/0.9 .12/org/jooq/lambda/tuple/package-summary.html – Henrik

回答

2

你可能會考慮以下解決方案:

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() + "]"; 
    } 
} 
3

您可以創建多個構造函數,可以做你想要做什麼:

例如:

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

constructorshere

希望這可以幫助你。

+0

謝謝,但Tuple2和Tuple3必須是一個類。 – hqid

+1

@hqid,是的,那麼你可以創建類與我以前做不同的構造函數 –

2

您可以製作Tuple2<T1, T2, T3>以及類似的Tuple3。您可以將Tuple1<T1, T2>作爲Tuple2中的私有字段與T3 c一起存儲,並實現所有必需的方法,其中一些方法將其調用委託給適當的Tuple1方法。它看起來可能是多餘的,但你需要聲明一個方法來調用它,所以沒有辦法避免這種情況。