java基础知识: day13-泛型 <T> Generics

概述

泛型,即参数化类型,将具体的类型定义成参数形式(类型形参)。是 JDK 5 中引入的一个新特性,泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型,泛型只存在于编译期间,编译后类型会被擦除,被Oject代替。

// 基础语法
class 类型名<泛型标示符:可以随意写合法的字符>{
    private 泛型标识符 var;
}
复制代码
类型形参的规则
  • T : List 指定类型

  • ? : List<? extend E> -- 接受E或者E的子类 List<? super E> -- 接受E或者E的父类

  • Object : 任意类型,好像没有什么意思。

3个使用方式
泛型类

直接上例子

public class Box<T> {

    private T object;

    public void set(T object) {
        this.object = object;
    }

    public T get() {
        return object;
    }

    public static void main(String[] args) {
        Box<String> box1 = new Box<>();
        box1.set("hello world ~");
        System.out.println(box1.get());
    }

}
复制代码
泛型接口

直接上例子

public interface Mymap<K, V> {
    public K getKey();
    public V getValue();
}

public class MymapImpl<K, V> implements Mymap<K, V> {

    private K key;
    private V value;

    public MymapImpl(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public static void main(String[] args) {
        Mymap<String, Integer> mp1 = new MymapImpl<String, Integer>("ESds", 23);
        Mymap<String, String> mp2 = new MymapImpl<String, String>("hello", "world");
        Mymap<Integer, Integer> mp3 = new MymapImpl<Integer, Integer>(232, 888);
    }
}
复制代码
泛型方法

直接上例子

public class Box<T> {

    private T object;

    public void set(T object) {
        this.object = object;
    }

    public T get() {
        return object;
    }
    
    // 定义泛型方法
    public <T1> void printBox(T1 x) {
        T1 m = x;
        System.out.println("This box is:" + m);
    }

    public static void main(String[] args) {
        Box<String> box1 = new Box<>();
        Box<Integer> box2 = new Box<>();
        box1.printBox(box2);
    }

}
复制代码
类型擦除

编译器虽然会在编译过程中移除参数的类型信息,但是会保证类或方法内部参数类型的一致性。

// 泛型"擦除"
// 编译器虽然会在编译过程中移除参数的类型信息,但是会保证类或方法内部参数类型的一致性。
Class<?> boxClass1 = new Box<String>().getClass();
Class<?> boxClass2 = new Box<Long>().getClass();
System.out.println(boxClass1);
System.out.println(boxClass2);

输出:
class day13.Box
class day13.Box
复制代码

转载于:https://juejin.im/post/5cb01e52e51d456e8a12ef6a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值