通過泛型方法簡化元組的創(chuàng)建
通過泛型的類型參數(shù)推導(dǎo)判斷,再加上static方法,可以編寫出一個(gè)更方便的元組工具用于創(chuàng)建元組。
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類是用于測(cè)試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()返回的是一個(gè)參數(shù)化的TwoTuple對(duì)象,而f2()返回的是非參數(shù)化的TwoTuple對(duì)象。而在這里編譯器并沒有發(fā)出警告信息,這是因?yàn)檫@里沒有將其返回值作為一個(gè)參數(shù)化對(duì)象使用。而在某種意義上,它被"向上轉(zhuǎn)型"作為一個(gè)非參數(shù)化的TwoTuple。這個(gè)時(shí)候,如果試圖將f2()的返回值轉(zhuǎn)型為參數(shù)化的TwoTuple,編譯器就會(huì)發(fā)出警告。