Java中的范型

1、定义和使用含有范型的类

首先定义含有范型的类

public class GenericClass<E> {
    private E name;

    public E getName() {
        return name;
    }

    public void setName(E name) {
        this.name = name;
    }
}

使用含有范型的类

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

        //创建GenericClass对象,范型使用Integer类型
        GenericClass<Integer> gc = new GenericClass<>();
        gc.setName(1);
        Integer name = gc.getName();
        System.out.println(name);


        //创建GenericClass对象,范型使用String类型
        GenericClass<String> gc2 = new GenericClass<>();
        gc2.setName("hello");
        String name2 = gc2.getName();
        System.out.println(name2);
    }
}

2、定义和使用含有范型的方法

首先定义含有范型的方法

public class GenericMethod {

    //含有范型的方法
    public <E> void func(E e){
        System.out.println(e);
    }

    //含有范型的静态方法
    public static <M> void func2(M m){
        System.out.println(m);
    }

}

然后使用含有范型的方法

GenericMethod gm = new GenericMethod();
        gm.func("hello");
        gm.func(12);
        gm.func(9.9);
        gm.func(true);

        GenericMethod.func2("world");
        GenericMethod.func2(13);

3、范型通配符

public class Test03 {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<>();
        list1.add(8);
        list1.add(9);

        ArrayList<String> list2 = new ArrayList<>();
        list2.add("hello");
        list2.add("world");

        printArrayList(list1);
        printArrayList(list2);
    }
    //定义一个方法可以遍历所有类型的ArrayList集合,范型通配符只能在参数传递时使用,而不能在定义的时候使用
    public static void printArrayList(ArrayList<?> list){
        Iterator<?> it = list.iterator();
        while(it.hasNext()){
            Object obj = it.next();
            System.out.println(obj);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值