元组是将一组对象直接打包存储于其中的一个单一对象。
这个容器对象允许读取其中元素,但是不允许向其中放入新的对象。
下面是一个二维元组,能够持有两个对象:
public class TwoTuple<A,B> {
//first可以访问,但不可以被赋值
public final A first;
public final B second;
public TwoTuple(A a,B b){
first=a;
second=b;
}
public String toString(){
return "("+first+","+second+")";
}
}
扩大元组:
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+")";
}
}
测试:
class Amphibian{}
public class TupleTest {
static TwoTuple<String,Integer> f(){
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";//错误,final无法修改
System.out.println(g());
}
}