posts - 397,comments - 0,views - 25332

定义含有泛型的方法:泛型定义在方法的修饰符和返回值类型之间

格式:

修饰符<泛型>返回值类型方法名(参数列表(使用泛型)){

方法体;

}

含有泛型的方法,在调用方法的时候确定泛型的数据类型

传递什么类型的参数,泛型就是什么类型

代码举例:

复制代码
public class GenericMethod {

    public <M> void method(M m){
        System.out.println(m);
    }

    public static <S> void method2(S s){
        System.out.println(s);
    }
}

public class Demo03GenericMethod {

    public static void main(String[] args) {


        GenericMethod genericMethod = new GenericMethod();
        genericMethod.method(10);
        genericMethod.method("abc");
        genericMethod.method(8.8);
        genericMethod.method(true);

        genericMethod.method2("静态方法,不建议创建对象使用");
        genericMethod.method2("静态方法");
        genericMethod.method2(1);
    }
复制代码

 

 

 

泛型通配符:

?:代表任意的数据类型使用方式:

不能创建对象使用

只能作为方法的参数使用

代码举例1:

 

 

代码举例2:

 

 

 

代码举例3:

 public void addAll(Gys<? extend T> cs){
    for(int i=0;i<cs.size();i++){
      add(cs.get(i));
    }
}

代码举例4:

泛型上下限定

复制代码
public static void main(String[] args) {

        Collection<Integer> list1 = new ArrayList<Integer>();
        Collection<String> list2 = new ArrayList<String>();
        Collection<Number> list3 = new ArrayList<Number>();
        Collection<Object> list4 = new ArrayList<Object>();
        getE1(list1);
        getE1(list2);
        getE1(list3);
        getE1(list4);

        getE2(list1);
        getE2(list2);
        getE2(list3);
        getE2(list4);


    }

    public static void getE1(Collection<? extends Number> collection){

    }

    public static void getE2(Collection<? super Number> collection){

    }
复制代码

 

 

posted on   淤泥不染  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示