做为程序员是不是希望一次方法调用就可以返回多个对象,是的,我经常需要这样的做。可是return语句只支持返回单一对象。怎么办?那就创建一个对象,用它装载需要返回的对象,有点像容器的概念,这个容器只能读取,不可以向内新增对象。有了泛型后,我们就可以一次解决此问题了。
这个概念被称为元组。
public class TwoTuple<A, B> {
public final A first;
public final B second;
public TwoTuple(A a, B b) {
first = a;
second = b;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
}
我想要更长的元组怎么办?那就用java的继承
public class ThreeTuple<A, B, C> extends TwoTuple<A, B> {
public final C third;
public ThreeTuple(A a, B b, C c) {
super(a, b);
third = c;
}
public String toString() {
return "(" + first + ", " + second + ", " + third + ")";
}
}
为了使用元组,根据需求定义一个长度适中的元组,将其作为方法的返回值。
public class TupleTest {
static TwoTuple<String, Integer> f() {
// Autoboxing converts the int to Integer:
return new TwoTuple<String, Integer>("hi", 47);
}
static ThreeTuple<Amphibian, String, Integer> g() {
return new ThreeTuple<Amphibian, String, Integer>(new Amphibian(),
"hi", 47);
}
public static void main(String[] args) {
TwoTuple<String, Integer> ttsi = f();
System.out.println(ttsi);
// ttsi.first = "there"; // Compile error: final
}
}