泛型方法——简化元组的使用

通过泛型方法简化元组的创建

通过泛型的类型参数推导判断,再加上static方法,可以编写出一个更方便的元组工具用于创建元组。

public class Tuple {
    public static  TwoTuple tuple(A a, B b) {
        return new TwoTuple<>(a, b);
    }

    public static  ThreeTuple tuple(A a, B b, C c) {
        return new ThreeTuple<>(a, b, c);
    }

    public static  FourTuple tuple(A a, B b, C c, D d) {
        return new FourTuple<>(a, b, c, d);
    }

    public static  FiveTuple 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 f() {
        return tuple("h1", 47);
    }

    static TwoTuple f2() {
        return tuple("h1", 47);
    }

    static ThreeTuple g() {
        return tuple(new Amphibian(), "h1", 47);
    }

    static FourTuple h() {
        return tuple(new Vehicle(), new Amphibian(), "h1", 47);
    }

    static FiveTuple k() {
        return tuple(new Vehicle(), new Amphibian(), "h1", 47, 11.1);
    }

    public static void main(String[] args) {
        TwoTuple 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,编译器就会发出警告。

你可能感兴趣的:(泛型方法——简化元组的使用)