泛型类

类型作为参数传入到泛型类中。

  1. public class Point<T> {
  2. private T x;
  3. private T y;
  4. public T getX() {
  5. return x;
  6. }
  7. public void setX(T x) {
  8. this.x = x;
  9. }
  10. public T getY() {
  11. return y;
  12. }
  13. public void setY(T y) {
  14. this.y = y;
  15. }
  16. }

然后不能传入原生类型,要传入引用类型.所以想传入 int 就应该用包装类 Interger , 想用 double 就传入包装类 Double

  1. public class Test{
  2. public static void main(String[] args){
  3. // 坐标为int类型,把int类型的包装类Integer作为参数传入泛型类中
  4. Point<Integer> point1 = new Point<Integer>();
  5. point1.setX(1);
  6. point1.setY(1);
  7. // 坐标为double类型,把double类型的包装类Double作为参数传入泛型类中
  8. Point<Double> point2 = new Point<Double>();
  9. point2.setX(3.456);
  10. point2.setY(4.789);
  11. }
  12. }

多个泛型参数

比如实现一个三元组:

  1. public class Triple<A, B, C> {
  2. private A a;
  3. private B b;
  4. private C c;
  5. public A getA() {
  6. return a;
  7. }
  8. public void setA(A a) {
  9. this.a = a;
  10. }
  11. public B getB() {
  12. return b;
  13. }
  14. public void setB(B b) {
  15. this.b = b;
  16. }
  17. public C getC() {
  18. return c;
  19. }
  20. public void setC(C c) {
  21. this.c = c;
  22. }
  23. }