Java 泛型

1,泛型类
public class Holder<T> {
	private T a ;
	public Holder(T a){
		this.a = a;
	}
	public T getA() {
		return a;
	}
	public static void main(String[] args) {
		Holder<String> h1 = new Holder<String>("12345678");
		System.out.println(h1.getA());
	}
}

当你创建Holder对象时,必须指明想持有什么类型的对象。

2,元组类型
元组:将一组对象直接打包存储于其中一个单一对象。这个容器对象允许读取其中元素但拒绝向其中存放新的对象。这个概念称为 数据传送对象或者 信使
class ThreeTuple<A, B, C> extends Tuple<A, B> {
	public final C third;

	public ThreeTuple(A a, B b, C c) {
		super(a, b);
		this.third = c;
	}

	@Override
	public String toString() {
		return "ThreeTuple [" + super.toString() + " third=" + third + "]";
	}
}

public class Tuple<A, B> {
	public final A first;
	public final B second;

	public Tuple(A a, B b) {
		this.first = a;
		this.second = b;
	}

	@Override
	public String toString() {
		return "Tuple [first=" + first + ", second=" + second + "]";
	}

	public static void main(String[] args) {
		Tuple<String, String> persons = new Tuple<String, String>("A", "B");
		System.out.println(persons);
		persons = new Tuple<String, String>("C", "D");
		System.out.println(persons);
		
		ThreeTuple<String, String, String> tp = new ThreeTuple<String, String, String>("a","b","c");
		System.out.println(tp);
	}
}


你可能感兴趣的:(java 泛型)