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

有时需要在方法末尾返回类型不同的对象,而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;}(String[] args) {Test test = new Test();ReturnTwo<String, Integer> rt = test.get();System.out.println(rt.first);System.out.println(rt.second);}}

输出结果: abc 123

人生好如足球赛,看自家总是无奈,对人家总是优待,

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

相关文章:

你感兴趣的文章:

标签云: