通过泛型方法简化元组的创建
通过泛型的类型参数推导判断,再加上static
方法,可以编写出一个更方便的元组工具用于创建元组。
public class Tuple {
public static <A, B> TwoTuple<A, B> tuple(A a, B b) {
return new TwoTuple<>(a, b);
}
public static <A, B, C> ThreeTuple<A, B, C> tuple(A a, B b, C c) {
return new ThreeTuple<>(a, b, c);
}
public static <A, B, C, D> FourTuple<A, B, C, D> tuple(A a, B b, C c, D d) {
return new FourTuple<>(a, b, c, d);
}
public static <A, B, C, D, E> FiveTuple<A, B, C, D, E> tuple(A a, B b, C c, D d, E e) {
return new FiveTuple<>(a, b, c, d, e);
}
}
以下的TupleTest2
类是用于测试Tuple
工具类的代码。
import static com.daidaijie.generices.tuple.Tuple.tuple;
public class TupleTest2 {
static TwoTuple<String, Integer> f() {
return tuple("h1", 47);
}
static TwoTuple f2() {
return tuple("h1", 47);
}
static ThreeTuple<Amphibian, String, Integer> g() {
return tuple(new Amphibian(), "h1", 47);
}
static FourTuple<Vehicle, Amphibian, String, Integer> h() {
return tuple(new Vehicle(), new Amphibian(), "h1", 47);
}
static FiveTuple<Vehicle, Amphibian, String, Integer, Double> k() {
return tuple(new Vehicle(), new Amphibian(), "h1", 47, 11.1);
}
public static void main(String[] args) {
TwoTuple<String, Integer> ttsi = f();
System.out.println("ttsi = " + ttsi);
System.out.println("f2() = " + f2());
System.out.println("g() = " + g());
System.out.println("h() = " + h());
System.out.println("k() = " + k());
}
}
// Outputs
ttsi = (h1, 47)
f2() = (h1, 47)
g() = (com.daidaijie.generices.tuple.Amphibian@1540e19d, h1, 47)
h() = (com.daidaijie.generices.tuple.Vehicle@677327b6, com.daidaijie.generices.tuple.Amphibian@14ae5a5, h1, 47)
k() = (com.daidaijie.generices.tuple.Vehicle@7f31245a, com.daidaijie.generices.tuple.Amphibian@6d6f6e28, h1, 47, 11.1)
这里要注意的是,方法f()
返回的是一个参数化的TwoTuple
对象,而f2()
返回的是非参数化的TwoTuple
对象。而在这里编译器并没有发出警告信息,这是因为这里没有将其返回值作为一个参数化对象使用。而在某种意义上,它被"向上转型"作为一个非参数化的TwoTuple
。这个时候,如果试图将f2()
的返回值转型为参数化的TwoTuple
,编译器就会发出警告。