泛型

类的泛型

1、创建集合对象,不使用泛型

好处:集合不使用泛型,默认的类型就是object类型,可以存储任意类型的数据。

弊端:不安全,会引发异常。

2、创建集合对象,使用泛型

好处:为了避免类型转换的麻烦,存储的是什么类型,取出的就是什么类型。

把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候就会报错)。

弊端:泛型是什么类型,就只能存储什么类型。

/**
* @program: intellij idea
* @description:定义一个含有泛型的类。泛型可以接受任意的数据类型。
* 创建对象的时候确定泛型的数据类型。
* @author: lixy
* @create: 2020-05-02 11:05
**/
public class MyGeneric<T> {
  private T name;

  public MyGeneric() {
  }

  public MyGeneric(T name) {
      this.name = name;
  }

  public T getName() {
      return name;
  }

  public void setName(T name) {
      this.name = name;
  }
}
        //不写泛型默认是object类型
      MyGeneric myGeneric = new MyGeneric();
      myGeneric.setName("heihei");
      Object obj = myGeneric.getName();

      //使用泛型,创建对象时确定类型,泛型使用Integer类型
      MyGeneric<Integer> stringMyGeneric = new MyGeneric<Integer>();
      stringMyGeneric.setName(1);
      Integer name = stringMyGeneric.getName();
      System.out.println(name);

含有泛型的方法

/**
* @program: intellij idea
* @description:定义含有泛型的方法:泛型定义在方法的修饰符和返回值之间。
* 含有泛型的方法,在调用方法的时候确定泛型的数据类型
* 传递什么类型的参数,泛型就是什么类型
* @author: lixy
* @create: 2020-05-02 16:03
**/
public class MyGenericMethod {
  //定义一个含有泛型的方法
  public <T> void method(T t){
      System.out.println(t);
  }
  //定义一个含有泛型的静态方法
  public static <T> void method02(T t){
      System.out.println(t);
  }
}
        MyGenericMethod myGenericMethod = new MyGenericMethod();
      myGenericMethod.method(1);
      myGenericMethod.method("hahha");
      //静态方法
      MyGenericMethod.method02(5);
      MyGenericMethod.method02("静态方法");

运行结果:
1
hahha
5
静态方法

含有泛型的接口

/**
* @program: intellij idea
* @description:定义含有泛型的接口
* @author: lixy
* @create: 2020-05-02 16:28
**/
public interface GenericInterface <T> {
  public abstract void method(T t);
}
//第一种泛型接口的使用方式:定义接口的实现类,实现接口,指定接口的泛型
public class GenericInterfaceImpl implements GenericInterface<String> {
  @Override
  public void method(String s) {
      System.out.println(s);
  }
}
/**
* @program: intellij idea
* @description:第二种泛型接口的使用方式:接口使用什么泛型,实现类就使用什么泛型,类跟着接口走
* 就相当于定义了一个含有泛型的类,创建对象的时候确定泛型的类型
* @author: lixy
* @create: 2020-05-02 16:40
**/
public class GenericInterfaceImpl02<T> implements GenericInterface<T> {
  @Override
  public void method(T t) {
      System.out.println(t);
  }
}
GenericInterfaceImpl genericInterface = new GenericInterfaceImpl();
genericInterface.method("jiekou1");
GenericInterfaceImpl02<Integer> impl02 = new GenericInterfaceImpl02<>();
impl02.method(555);

运行结果:
jiekou1
555
原文地址:https://www.cnblogs.com/lxy522/p/12818638.html