public class TwoTuple<A, B> {
public final A first;
public final B second;
public TwoTuple(A a, B b) {
first = a;
second = b;
}
@Override
public String toString() {
return "TwoTuple{" +
"first=" + first +
", second=" + second +
'}';
}
}
public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
public final C third;
public ThreeTuple(A a, B b, C c) {
super(a, b);
third = c;
}
@Override
public String toString() {
return "ThreeTuple{" +
"third=" + third +
", first=" + first +
", second=" + second +
'}';
}
}
public class FourTuple<A, B, C, D> extends ThreeTuple<A, B, C> {
public final D fourth;
public FourTuple(A a, B b, C c, D d) {
super(a, b, c);
fourth = d;
}
@Override
public String toString() {
return "FourTuple{" +
"fourth=" + fourth +
", third=" + third +
", first=" + first +
", second=" + second +
'}';
}
}
public class FiveTuple<A, B, C, D, E> extends FourTuple<A, B, C, D> {
public final E fifth;
public FiveTuple(A a, B b, C c, D d, E e) {
super(a, b, c, d);
fifth = e;
}
@Override
public String toString() {
return "FiveTuple{" +
"fifth=" + fifth +
", fourth=" + fourth +
", third=" + third +
", first=" + first +
", second=" + second +
'}';
}
}
public class Amphibian {
}
public class Vehicle {
}
1)方法的返回类型是泛型,方法的参数列表中没有泛型,故方法的返回值前不需要泛型参数列表;
public class TupleTest {
static TwoTuple<String, Integer> f() {
return new TwoTuple<String, Integer>("hi", 47);
}
static ThreeTuple<Amphibian, String, Integer> g() {
return new ThreeTuple<Amphibian, String, Integer>(
new Amphibian(), "hi", 47);
}
static FourTuple<Vehicle, Amphibian, String, Integer> h() {
return new FourTuple<Vehicle, Amphibian, String, Integer>(
new Vehicle(), new Amphibian(), "hi", 47);
}
static FiveTuple<Vehicle, Amphibian, String, Integer, Double> k() {
return new FiveTuple<Vehicle, Amphibian, String, Integer, Double>(
new Vehicle(), new Amphibian(), "hi", 47, 11.1);
}
public static void main(String[] args) {
TwoTuple<String, Integer> ttsi = f();
System.out.println(ttsi);
System.out.println(g());
System.out.println(h());
System.out.println(k());
}
}
输出
TwoTuple{first=hi, second=47}
ThreeTuple{third=47, first=chapter15._2._1.Amphibian@610455d6, second=hi}
FourTuple{fourth=47, third=hi, first=chapter15._2._1.Vehicle@511d50c0, second=chapter15._2._1.Amphibian@60e53b93}
FiveTuple{fifth=11.1, fourth=47, third=hi, first=chapter15._2._1.Vehicle@5e2de80c, second=chapter15._2._1.Amphibian@1d44bcfa}