泛型

参数化类型。就是将类型由原来的具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),然后在使用/调用时传入具体的类型(类型实参)。

  • 在编译之后程序会采取去泛型化的措施。Java中的泛型,只在编译阶段有效。

泛型类

不需要强制类型转换
提高了代码的复用率

  1. public class Person<A,B,T,D> {
  2. private A data;
  3. public A getData() {
  4. return data;
  5. }
  6. public void setData(A data) {
  7. this.data = data;
  8. }
  9. }

泛型接口

实现的时候可以选择指定类型,或者不指定类型。

  1. public interface Name<T> {
  2. T getData();
  3. }
  4. //不指定类型
  5. public class Interface1<T> implements Name<T>{
  6. private T text;
  7. @Override
  8. public T getData() {
  9. return text;
  10. }
  11. }

泛型方法

  1. public class Demo1 {
  2. public static void main(String[] args) {
  3. print("cnmcnm");
  4. }
  5. public static <A> void print(A a){
  6. System.out.println(a);
  7. }
  8. }

泛型限制类型

  1. public class Demo1 {
  2. public static void main(String[] args) {
  3. Plate<Apple> p = new Plate<>();
  4. }
  5. }
  6. interface Fruit{}
  7. class Apple implements Fruit{}
  8. class Plate<T extends Fruit>{
  9. T data;
  10. }

泛型中的通配符 ?

  1. public class Demo1 {
  2. public static void main(String[] args) {
  3. //上届限定,只能用父里面的子
  4. Plate<? extends Fruit> p = new Plate<Apple>();
  5. //下届限定
  6. Plate<? super Apple> p2 = new Plate<Fruit>();
  7. }
  8. }
  9. interface Fruit{}
  10. class Apple implements Fruit{}
  11. class Plate<T extends Fruit>{
  12. T data;
  13. }

java.util.Objects