JAVA利用泛型返回类型不同的对象

来源:互联网 发布:天正交通设施设计软件 编辑:程序博客网 时间:2024/05/10 22:44

有时需要在方法末尾返回类型不同的对象,而return 语句只能返回一个或一组类型一样的对象。此时就需要用到泛型。

首先先解释个概念,
元组: 它是将一组对象直接打包存储于其中的一个单一对象,这个容器对象允许读取其中元素,但不能修改。

利用泛型创建元组

public class ReturnTwo<A,B> {    public final A first;    public final B second;    public ReturnTwo(A a,B b) {        first = a;        second = b;    }}

测试

public class Test {    private String a = "abc";    private int b = 123;    public ReturnTwo<String, Integer> get() {        ReturnTwo<String, Integer> rt = new ReturnTwo<String, Integer>(this.a, this.b);        return rt;    }    public static void main(String[] args) {        Test test = new Test();        ReturnTwo<String, Integer> rt = test.get();        System.out.println(rt.first);        System.out.println(rt.second);    }}

输出结果:

abc 123
4 0
原创粉丝点击