初入Java元组,自己编写了个元组工具类,与大家共享一下

今天读了Thinking in Java后突发奇想,写了个元组工具类,可以往下无限扩展,与大家共享下,如有不足之处欢迎指正。
/**
 * Created by kangtaiyang on 2018/6/8.
 */
public class Tuple {

    private TwoTuple two;
    private ThreeTuple three;
    private FourTuple four;

    public <A, B> Tuple(A a, B b) {
        this.two = getTuple(a, b);
    }

    public <A, B, C> Tuple(A a, B b, C c) {
        this.three = getTuple(a, b, c);
    }

    public <A, B, C, D> Tuple(A a, B b, C c, D d) {
        this.four = getTuple(a, b, c, d);
    }

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

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

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

    @Override
    public String toString() {
        if (two != null) {
            return two.toString();
        }
        if (three != null) {
            return three.toString();
        }
        if (four != null) {
            return four.toString();
        }
        return null;
    }

    static class TwoTuple<A, B> {
        public final A a;
        public final B b;

        public TwoTuple(A a, B b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public String toString() {
            return "TwoTuple{" +
                    "a=" + a +
                    ", b=" + b +
                    '}';
        }
    }

    static class ThreeTuple<A, B, C> extends TwoTuple {
        public final C c;

        public ThreeTuple(A a, B b, C c) {
            super(a, b);
            this.c = c;
        }

        @Override
        public String toString() {
            return "ThreeTuple{" +
                    "a=" + a +
                    ", b=" + b +
                    ", c=" + c +
                    '}';
        }
    }

    static class FourTuple<A, B, C, D> extends ThreeTuple {
        public final D d;

        public FourTuple(A a, B b, C c, D d) {
            super(a, b, c);
            this.d = d;
        }

        @Override
        public String toString() {
            return "FourTuple{" +
                    "a=" + a +
                    ", b=" + b +
                    ", c=" + c +
                    ", d=" + d +
                    '}';
        }
    }

    public TwoTuple getTwo() {
        return two;
    }

    public ThreeTuple getThree() {
        return three;
    }

    public FourTuple getFour() {
        return four;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37580283/article/details/80628269
今日推荐