java泛型程序

泛型

<一>为什么需要泛型

泛型是jdk5引入的,泛型程序能够让程序更安全,在编译期间就去校验数据的合法性。一个小demo:

        //当在构造集合时不指定泛型类型,集合中可以存放所有的Object对象
        ArrayList array = new ArrayList();
        array.add("test1");
        array.add(234);
        array.add(new Person("张三",13));
        array.add('A');
        array.forEach(obj->{
            System.out.println(obj);
        });

这样的程序跑起来很容易成bug,为什么?看看脚本语言javaScript的遍历:

const arr = [];
arr.push("test1",234,{name:"张三",age:13},'A');
arr.forEach(obj=>{
    console.log(obj)
})

如果没有泛型,强类型的语言java也可能变得“弱类型”语言,js中最容易出现的问题就是类型问题,这种问题给程序带来的问题很多,因此我们希望在编译期间就去检查类型而不是在运行期间。

同时泛型程序可以让我们写出扩展性更高的程序。

<二>泛型类&泛型接口

1,泛型类
1.1,基本使用
public class GenericClazz <T>{ //具体类型将在new 时指定
    private T name;
    public GenericClazz(T name){
        this.name = name;
    }
    public GenericClazz(){
    }
    public T getName(){
        return this.name;
    }
    public void setName(T name){
        this.name = name;
    }
}
    @Test
    public void test2(){
        GenericClazz<Object> objectGenericClazz = new GenericClazz<>();
        objectGenericClazz.setName(new Person("yby",21));
        System.out.println(objectGenericClazz.getName());

        GenericClazz<String> objectGenericClazz2 = new GenericClazz<>("张三");
        System.out.println(objectGenericClazz2.getName());
    }

从上面可以看出,泛型类的可扩展性很高。

1.2,泛型派生类的几种情况
1.2.1,父类是泛型类的情况
//一,当子类也是泛型类时,子类的泛型标识符必须和父类一致
class ChildGeneric<T> extends FatherGeneric<T>{}

//二,当子类有多个泛型标识符时,必须有一个与父类一致
class ChildGeneric<T,K,E> extends FatherGeneric<T>{}

//三,当子类不是泛型类时,父类必须指明泛型的具体类型
class ChildGeneric extends FatherGeneric<Person>{}
1.2.2,父类不是泛型类
//一,子类是泛型类,此时会默认父类为Object类型
class ChildGeneric<T> extends FatherGeneric{}
2,泛型接口
1.1,语法
interface 接口名<泛型标识,...>{
   泛型标识 方法名(参数类型 参数名,...);
   //与泛型类差不多,返回值可以是void
}
1.2,使用规则

基本上和泛型类的使用一致。(将implements当做extends去理解)

<三>泛型方法

1,语法

访问修饰符 <泛型标识> 返回值类型 方法名(泛型标识 参数名,…){};

泛型方法可以声明为static,但是泛型类中的成员不能声明为static。

泛型方法中的泛型标识与泛型类中的泛型标识相互独立。

泛型方法的类型在调用时确定。

2,泛型方法的使用
   //泛型方法
    public <T> void print(T t){
        System.out.println("泛型类型是: "+t.getClass().getTypeName());
    }
    //static泛型方法
    public static <T> void  print2(T t) {
        System.out.println(t.toString());
        System.out.println("泛型标识的具体类型是: "+t.getClass().getTypeName());
    }
    //泛型方法与可变参数
    public <E> void myForEach(E... e){
        for (E ele:e) {
            System.out.println(ele);
        }
    }
    @Test
    public void test3(){
        GenericTest test = new GenericTest();

        test.print(new Person());  //com.jdk8.learn.bean.Person
        test.print(23); //java.lang.Integer
        test.print("你好");  //java.lang.String

        //Person{name='yby', age=21}
        //泛型标识的具体类型是: com.jdk8.learn.bean.Person
        GenericTest.print2(new Person("yby",21));
        
        test.myForEach(12,123,54,235,856,345,762,235);
    }

<四>泛型通配符

泛型通配符 ‘ ?’ 指代具体的类型。

1,快速开始
    public static  void log(GenericClazz<?> type){
        System.out.println(type.toString());
        System.out.println("当前调用者的数据类型是 :"+type.getClass().getTypeName());
    }
    @Test
    public void test4(){
        GenericClazz<Person> genericClazz = new GenericClazz<>();
        genericClazz.setName(new Person("yby",21));

        //GenericClazz{name=Person{name='yby', age=21}}
        //当前调用者的数据类型是 :com.jdk8.learn.generic.GenericClazz
        GenericTest.log(genericClazz);
    }
2,类型通配符的上限
2.1,定义语法

类<? extends 实参类型> 或 接口<? extends 实参类型>。

2.2,使用
public class Animal {}

public class Cat extends Animal{}

public class MiniCat extends Cat{}
    /*
      泛型通配符的上限的使用
     */
    public static void showAnimal(ArrayList<? extends Cat> list){
        //不管添加谁都会报错,因为此时传递的 实参? 还没确定是什么类型
        // list.add(new Cat("test"));
        // list.add(new MiniCat("test2"));
        // list.add(new Animal());

        list.forEach(e->{
            System.out.println(e.toString());
        });
    }
    @Test
    public void test5(){
        ArrayList<Animal> animals = new ArrayList<>();
        ArrayList<Cat> cats = new ArrayList<>();
        ArrayList<MiniCat> miniCats = new ArrayList<>();

        animals.add(new Animal());
        cats.add(new Cat("Tom"));
        miniCats.add(new MiniCat("Mini Tom"));

        //showAnimal(animals); ---> 编译报错,因为: 该方法传递参数的上限是Cat类型
        showAnimal(cats);
        showAnimal(miniCats);
    }
3,泛型通配符的下限
3.1,定义语法

类<? super 实参类型> 或 接口<? super 实参类型>。

3.2,使用
    /*
      泛型通配符的下限的使用
     */
    public static void showAnimal2(ArrayList<? super Cat> list){
        list.forEach(e->{
            System.out.println(e.toString());
        });
    }
    @Test
    public void test6(){
        ArrayList<Animal> animals = new ArrayList<>();
        ArrayList<Cat> cats = new ArrayList<>();
        ArrayList<MiniCat> miniCats = new ArrayList<>();

        animals.add(new Animal("Jerry"));
        cats.add(new Cat("Tom"));
        miniCats.add(new MiniCat("Mini Tom"));

        showAnimal2(animals);
        showAnimal2(cats);
        //showAnimal2(miniCats); ---> 编译报错,因为: 该方法传递参数的下限是Cat类型
    }

<五>泛型擦除

由于泛型是JDK5才引进的,为了兼容之前的版本,泛型信息只会存在编译阶段,进入JVM之前,与泛型相关的信息会被擦除。

1,无限制的擦除
public class Erasure<T>{                        >               public class Erasure{       
    private T name;                             >                   private Object name;
    public T getName(){                         >                   public Object getName(){
        return this.name;           ------------>                       return this.name;
    }                               | 泛型擦除后 |>                   }
    public void setName(T t){       ------------>                   public void setName(Object t){
        this.name = t;                          >                        this.name = t; 
    }                                           >                   }
}                                               >               }
2,有限制的擦除
public class Erasure<T extends Number>{         >               public class Erasure{       
    private T name;                             >                   private Number name;
    public T getName(){                         >                   public Number getName(){
        return this.name;           ------------>                       return this.name;
    }                               | 泛型擦除后 |>                   }
    public void setName(T t){       ------------>                   public void setName(Number t){
        this.name = t;                          >                        this.name = t; 
    }                                           >                   }
}                                               >               }
3,桥接方法
    public interface Info<T>{
        T info<T t>;
    }
    
    public class InfoImpl implements Info<Integer>{
        public Integer info(Integer i){
            return i;
        }
    }

为了保持接口和类的实现一致,编译器会将擦除后,将Object强转为Integer类型,因此生成一个桥接方法。

    public interface Info<T>{
        T info<T t>;
    }
    
    public class InfoImpl implements Info{ 
        //桥接方法
        @Override
        public Object info(Object i){
            return info((Integer) i);
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Avalon712

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值