java元组实现方式之一

二维元组
public class TwoTuple {
    public final A first;
    public final B second;

    public TwoTuple(A first, B second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public String toString() {
        return "("+first+","+second+")";
    }
}
测试代码
public class TupleTest {
    public static void main(String[] args) {
        TwoTuple twoTuple = new TwoTuple<>(new Person("zhangsan", "male"), new Dog("dog", "black"));
        System.out.println(twoTuple.toString());
    }
}
测试结果
(Person{name='zhangsan', sex='male'},Dog{kind='dog', color='black'})
多维拓展(三维)
public class ThreeTuple extends TwoTuple {
    public final C third;

    public ThreeTuple(A first, B second, C third) {
        super(first, second);
        this.third = third;
    }

    @Override
    public String toString() {
        return "("+first+","+second+","+third+")";
    }
}

你可能感兴趣的:(java元组实现方式之一)