泛型

概述

数据类型的参数化,将类型定义成参数形式,在使用时传入参数。


类的泛型

(注意:一旦在类上声明泛型,在类里面所有非静态成员上都可以使用)
类的泛型,定义格式如下:

    public class 类名<T【A,B,C..】>{
      private T 变量名;

      public T 方法名(【T 形参名1,...】){
        //方法体
      }
    }

类的泛型中,类型参数决定该类中的成员变量的数据类型、也可以决定该类中成员方法的返回值类型。

使用一个例子说明,定义一个带泛型的Fruit类

public class Fruit<T> {
    private T f;
    public void setT(T f){
        this.f = f;
    }
    public T getT(){
        return f;
    }
}

定义一个Apple类

public class Apple {

    public String toString(){
        return "苹果";
    }
}

测试类和测试类结果如下

public class FanxingTest {
    public static void main(String[] args) {

        Fruit<Apple> f1 = new Fruit<>();
        f1.setT(new Apple());
        System.out.println(f1.getT());
    }

}


方法传参的泛型

    //有返回值方法
    public <T> T 方法名(T 参数名1【,...】){}

    //无参方法
    public <T> void 方法名(T 参数名1【,...】){}

通过一个例子说明:

public class Apple {

    public <T> T getData(T t){
        return t;
    }
    public <T> void printData(T t){
        System.out.println(t);
    }
}

测试类及结果如下:

public class FanxingTest {
    public static void main(String[] args) {
        Apple a = new Apple();
        a.printData(123);
        System.out.println(a.getData("aaa"));
    }

}


接口的泛型

同类一样,接口的泛型参数常命名为T,定义格式如下:

    public interface 接口名1<T【A,B,C..】>{
      T 方法名1();
    }

实现接口可以传入泛型实参,也可以不传:
传入实参,数据类型1,代码如下:

    public class 类名 implememts 接口名1<数据类型1【,数据类型2,数据类型3...】>{
      public 数据类型1 方法名1(){
        //方法体
      }
    }

不传入实参,代码如下:

    public class 类名 implements 接口名1<数据类型1【,数据类型2,数据类型3...】>{
      public 数据类型1 方法名1(){
        //方法体
      }
    }

泛型限定

通过泛型限定可以限制泛型的使用范围。

定义格式:

  //限定传入的泛型类型必须是某个类或接口的子接口
  <T extends 类名/接口名【,T extends 类名/接口名】>

  //限定传入的泛型类型必须时某个类的父类或接口的子接口
  <T super 类名/接口名【,T super 类名/接口名】>

泛型中的通配符

    public static void main(String[] args) {
        //泛型的上界限定,限定传入的参数只能是 Waste 的 子类
        Dustbin<? extends Waste,? extends Waste> dustbin1 = new Dustbin<MedicalWaste,FoodWaste>();

        //泛型的下界限定,限定传入的参数只能是 FoodWaste 的父类
        Dustbin<? super FoodWaste,? super FoodWaste> dustbin2 = new Dustbin<Waste,NonRecyclableWaste>();
    }
}
interface Waste{

}

interface NonRecyclableWaste extends Waste{
    
}
class Dustbin<T,C>{

}
class MedicalWaste implements NonRecyclableWaste{

}
class FoodWaste implements NonRecyclableWaste{

}
posted on 2021-10-09 22:42  技术小伙伴  阅读(13)  评论(0)    收藏  举报