Java 工具类(泛型:仅一次调用返回多个对象)

来源:互联网 发布:jmeter 安装mac版 编辑:程序博客网 时间:2024/05/29 13:08

一、场景分析:

需要仅一次方法调用就能返回多个对象。解决方法是创建一个对象,用它来持有想要返回的多个对象。当然,可以在每次需要的时候,专门创建一个类来完成这样的工作。这里通过泛型来编写一个通用的工具类,能够一次性解决该问题。

一个对象中返回多个对象的概念称为元组(tuple),它是将一组对象直接打包存储于其中的一个单一对象。这个容器对象只允许读取其中元素,而不允许向其中存放其它的对象。

       通常,元组可以有任意长度,同时,元组中的对象可以是任意不同的类型。

二、代码实现如下:

(1)工具类的结构如下:


我们在工具类utils下新建一个package包tuple,然后,在其中分别创建2维元组TwoTuple类,3维元组ThreeTuple类,4维元组FourTuple类,5维元组FiveTuple,还有一个测试类TupleTest。

(2)具体的代码如下:

2维元组类TwoTuple.java 代码如下:

public class TwoTuple<A, B> {    public final A first;    public final B second;    public TwoTuple(A a, B b){        this.first = a;        this.second = b;    }    public String toString(){        return "(" + first + ", " + second + ")";  

3维元组类ThreeTuple.java 代码如下:

public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {    public final C third;    public ThreeTuple(A first, B second, C third){        super(first, second);   //这个要先写        this.third = third;    }    public String toString(){        return "(" + first + ", " + second + ", " + third + ")";    }}

4维元组类FourTuple.java 代码如下:

public class FourTuple<A, B, C, D> extends ThreeTuple<A, B, C> {    public final D fourth;    public FourTuple(A first, B second, C third, D fourth){        super(first, second, third);        this.fourth = fourth;    }    public String toString(){        return "(" + first + ", " + second + ", " + third + ", " + fourth + ")";    }}

5维元组类FiveTuple.java 代码如下:

public class FiveTuple<A, B, C, D, E> extends FourTuple<A, B, C, D> {    public final E fifth;    public FiveTuple(A first, B second, C third, D fourth, E fifth){        super(first, second, third, fourth);        this.fifth = fifth;    }    public String toString(){        return "(" + first + ", " + second + ", " + third +", " + fourth + ", " + fifth + ")";    }}

针对上述的几个元组编写的测试代码TupleTest.java 类如下:
public class TupleTest {    static TwoTuple<String, Integer> f(){        return new TwoTuple<String, Integer>("hi", 47);    }    static ThreeTuple<String, Integer, Character> g(){        return new ThreeTuple<String, Integer, Character>(new String("tim"), 56, 'c');    }    static FourTuple<String, Long, Integer, Integer> h(){        return new FourTuple<String, Long, Integer, Integer>("hello", 13L, 33, 2);    }    static FiveTuple<String, Long, Long, String, String> k(){        return new FiveTuple<String, Long, Long, String, String>("tim11", 34L, 33L, "dd", "ee");    }    public static void main(String[] args) {        TwoTuple<String, Integer> ttsi = f();//        ttsi.first = "there";  //编译期运行错误:因为first虽然被声明为public但是final        System.out.println(g());        System.out.println(h());        System.out.println(k());    }}

分析:

public final A first;这样的声明虽然将字段声明为public,但是又因为声明了为final,因此,外部不能将其改变,如果设置新的值时,在编译期就会报错。










阅读全文
0 0
原创粉丝点击