java泛型知识总结

1. 什么是泛型?

泛型是JDK 5中引入的一个新特性,泛型提供了编译时类型安全监测机制,该机制允许程序员在编译时监测非法的类型。说白了就是 更好的安全性和可读性

2. 泛型正常分为三类

1. 泛型类
2. 泛型方法
3. 泛型接口

3. 泛型类

/*
 E表示集合的元素类型
 */

public class GenericClass<E> {
    // name是E类型的,如E为String类型
    private E name;

    // 返回E类型的name
    public E getName() {
        return name;
    }

    // 对于参数为E类型的name进行操作
    public void setName(E name) {
        this.name = name;
    }
}

测试:

public class GenericDemo {
    public static void main(String[] args) {
        // 创建对象时候指定为String类型
        GenericClass<String> genericClassString = new GenericClass<>();
        genericClassString.setName("泛型为Stirng类型");
        System.out.println(genericClassString.getName());
        // 创建对象时候指定为Interger类型
        GenericClass<Integer> genericClassInteger = new GenericClass<>();
        genericClassInteger.setName(123);
        System.out.println(genericClassInteger.getName());
    }
}

输出:

4.泛型方法

/*
    定义含有泛型的方法
    格式:
        修饰符 <泛型> 返回值类型 方法名称(参数列表(使用泛型)){
            方法体;
        }
 */
public class GenericClassMethod {
    // 前面的<E>告诉jvm,我一会有一个E类型的参数要使用,别给我报错!
    // 参数位置E m表示 ---> E类型的参数m
    public <E> void method(E m) {
        System.out.println(m);
    }
}

测试:

public class GenericDemo {
    public static void main(String[] args) {
        GenericClassMethod genericClassMethod = new GenericClassMethod();
        // 接收String类型的参数
        genericClassMethod.method("abc");
        // 接收Integer类型的参数
        genericClassMethod.method(123);
        // 接收Boolean类型的参数
        genericClassMethod.method(true);
    }
}

输出:
在这里插入图片描述

5.泛型接口

定义接口

/*
    接口限制为泛型I
 */
public interface GenericClassInterface<I> {
    public abstract void method(I i);
}

接口实现类

/*
    当实现类提前指定接口类型,可以省略实现类的泛型,如:
    public class GenericClassInterfaceImpl implements GenericClassInterface<String> {
        //...
    }
    否则依旧保持实现类中的泛型与接口泛型一致
 */
public class GenericClassInterfaceImpl<I> implements GenericClassInterface<I> {
    @Override
    public void method(I i) {
        System.out.println(i);
    }
}

测试:

public class GenericDemo {
    public static void main(String[] args) {
        GenericClassInterfaceImpl<String> gc1 = new GenericClassInterfaceImpl<>();
        gc1.method("abc");
        GenericClassInterfaceImpl<Integer> gc2 = new GenericClassInterfaceImpl<>();
        gc2.method(123);
        GenericClassInterfaceImpl<Boolean> gc3 = new GenericClassInterfaceImpl<>();
        gc3.method(true);
    }
}

输出:
在这里插入图片描述

6.总结

手动实现一次,很容易理解,终于搞懂了泛型,准备下一篇高级进阶。
链接:泛型的通配及泛型上下界<? extends T>和 <? super T>

发布了103 篇原创文章 · 获赞 55 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/l8947943/article/details/104155724