定义和使用含有泛型的类和方法

定义和使用含有泛型的类

定义一个含有泛型的类,模拟ArrayList集合

泛型是一个未知的数据类型,当我们不确定什么什么数据类型的时候,可以使用泛型

泛型可以接收任意的数据类型,可以使用Integer,String,Student...

创建对象的时候确定泛型的数据类型

复制代码
public class GenericClass<E> {
    private E name;

    public E getName() {
        return name;
    }

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

}
复制代码
复制代码
public class GenericClassTest {
    public static void main(String[] args) {
        //创建GenericClass对象
        GenericClass<Integer> gc2 = new GenericClass<>();
        gc2.setName(10);
        Integer name = gc2.getName();
        System.out.println(name);
    }
}
复制代码

 

定义和使用含有泛型的方法

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

格式:

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

    方法体;

  }

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

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

public class GenericMethod {
    //定义一个含有泛型的方法
    public <M> void Methods(M m){
        System.out.println(m);
    }
}
public class GenericMethodTest {
    public static void main(String[] args) {
        GenericMethod method = new GenericMethod();
        method.Methods("张三");
        method.Methods(2);
        method.Methods(1.1);
    }
}

 

 

    //定义一个含有泛型的静态方法
    public static <S> void Methods2(S s){
        System.out.println(s);
    }
GenericMethod.Methods2("李四");
GenericMethod.Methods2(1);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   魔光领域  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示