JAVA泛型——泛型类、泛型接口、泛型方法、泛型集合

  • JAVA泛型是jdk1.5引入的一个新特性,本质是参数化类型,把类型作为参数传递
  • 常见的有:泛型类、泛型接口、泛型方法
  • 语法:<T,...>T表示类型占位符,表示一种应用类型
  • 好处1、提高代码重用。2、防止类型转换异常,提高代码安全性。

1、泛型类

2、泛型接口

3、泛型方法

//泛型类
//类名<T>,T是占位符,表示一种引用类型,可以多个
//不同类型泛型对象不能相互复制
class MyGeneric<T> {
    //使用泛型
    T t;
    //泛型作为方法的参数
    public void show(T t){
//        T t1 = new T();   //不能实例化
        System.out.println(t);
    }
    //泛型作为方法的返回值
    public T getT(){
        return t;
    }
}

//泛型接口
//接口名<T>
interface MyInterface<T>{
    String name = "张三";
    T server(T t);
}
//实现时泛型类型确定
class MyInterfaceClass implements MyInterface<String>{
    @Override
    public String server(String t) {
        System.out.println(t);
        return t;
    }
}
//实现时泛型类型不确定
class MyInterfaceClass2<T> implements MyInterface<T>{
    @Override
    public T server(T t) {
        System.out.println(t);
        return t;
    }
}

//泛型方法
//<T> 返回值类型
class TestGenericMethod{
    //泛型方法
    public <T> void show(T t){
        System.out.println("泛型方法"+t);
    }
}
public class TestGeneric {
    public static void main(String[] args) {
        //创建泛型类对象
        MyGeneric<String> myGeneric = new MyGeneric<String>();
        myGeneric.t = "hello";
        System.out.println(myGeneric.getT());
        myGeneric.show("aaaaa");

        MyGeneric<Integer> myGeneric2 = new MyGeneric<Integer>();
        myGeneric2.t = 10;
        myGeneric2.show(200);
        System.out.println(myGeneric2.getT());

        //实现泛型接口
        MyInterfaceClass myInterfaceClass = new MyInterfaceClass();
        myInterfaceClass.server("aaaaaaaaaaa");
        MyInterfaceClass2<String> stringMyInterfaceClass2 = new MyInterfaceClass2<>();
        stringMyInterfaceClass2.server("aaaaaa");

        //泛型方法
        TestGenericMethod testGenericMethod = new TestGenericMethod();
        testGenericMethod.show("aaaa");
        testGenericMethod.show(111);
        testGenericMethod.show(new Student("aaa",19));


    }
}

泛型集合

参数化类型、类型安全的集合。强制集合的元素的类型必须一致

特点

  • 编译时即可检查,非运行时抛出异常
  • 访问时不必类型转换
  • 不同泛型之间引用不能相互赋值,泛型不存在多态
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

上兵伐眸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值