• 泛型基础使用


    现象:
    泛型基础使用

    泛型本质

    在创建对下或调用方法的时候才明确下具体的类型

    参数类型可以用在类、接口和方法中,分别被称为泛型类、泛型接口、泛型方法。

    优点:

    代码简洁、重复使用、保证了类型的安全性、消除强制转换、避免了不必要的装箱、拆箱操作,提高程序的性能

    例:

    集合的使用

    list list= new ArrayList<>();

    list.add(“Str”)

    泛型类

    在这里插入图片描述

    //泛型类型必须是引用类型
    public class 类名 <泛型类型,...> {
        T:任意类型 type
        E:集合中元素的类型 element
        K:key-value形式 key
        V: key-value形式 value
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    例:

    public class TestGenericity  {
    
        private T name;
    
        public TestGenericity(T name) {
            this.name = name;
        }
    
        public T getName() {
            return name;
        }
    
        public void setName(T name) {
            this.name = name;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    泛型接口

    public <泛型类型> 返回类型 方法名(泛型类型 变量名) {
        
    }
    
    • 1
    • 2
    • 3

    接口:
    在这里插入图片描述

    public interface TestGenericityInterface{
        public void showValue(T value);
    
    }
    
    • 1
    • 2
    • 3
    • 4

    实现1:

    在这里插入图片描述

    public class TestGenericityClassIInteger implements TestGenericityInterface {
    
        @Override
        public void showValue(Integer value) {
            System.out.println(value);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    实现二:
    在这里插入图片描述

    public class TestGenericityClassString implements TestGenericityInterface {
    
        @Override
        public void showValue(String value) {
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    泛型方法

    public <代表泛型的变量 返回类型 方法名(参数) {
        
    }
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    public  T testGenercityMethod1(T t){
        System.out.println(t.getClass());
        System.out.println(t);
        return t;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    泛型通配符

    1. 无边界的通配符

    //表示类型参数可以是任何类型
    public class Apple{}

    2.固定上边界的通配符

    //表示类型参数必须是A或者是A的子类
    public class Apple{}

    3. 固定下边界的通配符

    //表示类型参数必须是A或者是A的超类型
    public class Apple{}

  • 相关阅读:
    mybatispuls 批处理 rewriteBatchedStatements=true
    connection is being used##server is in use and cannot be deleted
    自幂数的统计
    RabbitMQ学习-第一部分
    形态学操作—开运算
    JavaScript-Obfuscator4.0.0字符串阵列化Bug及修复方法
    pat_basic_1017 A除以B
    学习ASP.NET Core Blazor编程系列一——综述
    窗口类介绍
    C语言for循环必备练习题
  • 原文地址:https://blog.csdn.net/hcwbr123/article/details/126011193