泛型类
把类型作为参数传入到泛型类中。
public class Point<T> {private T x;private T y;public T getX() {return x;}public void setX(T x) {this.x = x;}public T getY() {return y;}public void setY(T y) {this.y = y;}}
然后不能传入原生类型,要传入引用类型.所以想传入 int 就应该用包装类 Interger , 想用 double 就传入包装类 Double
public class Test{public static void main(String[] args){// 坐标为int类型,把int类型的包装类Integer作为参数传入泛型类中Point<Integer> point1 = new Point<Integer>();point1.setX(1);point1.setY(1);// 坐标为double类型,把double类型的包装类Double作为参数传入泛型类中Point<Double> point2 = new Point<Double>();point2.setX(3.456);point2.setY(4.789);}}
多个泛型参数
比如实现一个三元组:
public class Triple<A, B, C> {private A a;private B b;private C c;public A getA() {return a;}public void setA(A a) {this.a = a;}public B getB() {return b;}public void setB(B b) {this.b = b;}public C getC() {return c;}public void setC(C c) {this.c = c;}}
