泛型能够帮助我们把【类型明确】的工作推迟到创建对象或调用方法的时候。

1. 泛型类

泛型类是把泛型定义在类上,当用户在使用时才需要把类型给确定下来,具体方法使用<>加一个未知数(通常是单个参数用T,或者两个参数用KV)。

2. 泛型方法

| ```java public class GenericMethod { public T show(T t) { System.out.println(“Show Hello!”); return t; }

  1. public static void main(String[] args) {
  2. GenericMethod genericMethod = new GenericMethod();
  3. String hello = genericMethod.show("Hello World!");
  4. Integer code = genericMethod.show(123);
  5. }

}

  1. | ```java
  2. public class GenericMethod {
  3. public <K, V> V display(K k, V v) {
  4. return v;
  5. }
  6. public static void main(String[] args) {
  7. GenericMethod genericMethod = new GenericMethod();
  8. Integer value = genericMethod.display("Hello", 123);
  9. }
  10. }

| | —- | —- |

3. 泛型的继承

泛型类在继承时,可以明确父类(泛型类)的参数类型,也可以不明确。

不借用泛型的情况下,我们在实现一个StudentComparator比较器时,需要通过判断传进来的参数类型是否是Student类:

| ```java public interface Comparator { Integer compare(Object o1, Object o2); }

  1. | ```java
  2. public class StudentComparator implements Comparator{
  3. @Override
  4. public Integer compare(Object o1, Object o2) {
  5. if (o1 instanceof Student && o2 instanceof Student) {
  6. return ((Student) o1).getAge() - ((Student) o2).getAge();
  7. }
  8. return null;
  9. }
  10. }

| | —- | —- |

使用泛型可以省略类型判断的步骤:

| ```java public interface Comparator { Integer compare(T o1, T o2); }

  1. | ```java
  2. public class StudentComparator
  3. implements Comparator<Student> {
  4. @Override
  5. public Integer compare(Student o1, Student o2) {
  6. return o1.getAge() - o2.getAge();
  7. }
  8. }

| | —- | —- |

当然我们还可以实现

4. 泛型通配符

5. 泛型擦除

5.1 泛型擦除 VS. 多态

6. 静态和泛型