我做了一些事:
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
,没有代码冗余。
发布于 2017-01-30 04:40:40
您可以考虑以下解决方案:
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() + "]";
}
}
发布于 2017-01-26 11:30:20
您可以创建多个构造函数,这些构造函数可以执行您想做的事情:
例如:
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教程中了解更多内容:快速入门
希望这能帮到你。
发布于 2017-01-26 11:48:49
您可以制作Tuple2<T1, T2, T3>
和类似的Tuple3。您可以将Tuple1<T1, T2>
作为私有字段与Tuple2一起存储在T3 c
中,并实现所有必需的方法,其中一些方法只是将调用委托给适当的Tuple1方法。这看起来似乎是多余的,但您确实需要声明一个方法才能调用它,因此没有办法避免这种情况。
https://stackoverflow.com/questions/41881274
复制相似问题