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));


    }
}

泛型集合

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

特点

  • 编译时即可检查,非运行时抛出异常
  • 访问时不必类型转换
  • 不同泛型之间引用不能相互赋值,泛型不存在多态

版权声明:本文为weixin_44153521原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。