JAVA泛型-泛型类的定义和使用

1. 泛型类的声明语法

class 类名 <泛型标识,泛型标识…>{
private 泛型标识 属性名;

}

常用的泛型标识 : T,E,K,V (对应符号的具体含义在后面进行补充)

2.自定义一个泛型类

2.1 定义一个泛型类

/**
 * author : northcastle
 * createTime:2021/10/18
 * 自定义泛型类
 */
public class MyGenerics<T> {
    //1.有一个普通的属性
    private int num;
    //2.有一个泛型类型的属性
    private T t;

    //3.正常的构造方法
    public MyGenerics() {
    }

    public MyGenerics(int num, T t) {
        this.num = num;
        this.t = t;
    }

    //4.正常的getter/setter 方法
    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

    //5.正常的toString 方法

    @Override
    public String toString() {
        return "MyGenerics{" +
                "num=" + num +
                ", t=" + t +
                '}';
    }
}

2.2 在程序中使用泛型类

/**
 * author : northcastle
 * createTime:2021/10/18
 * 使用自定义的泛型类
 */
public class Application {
    public static void main(String[] args) {
        //1.创建一个自定义泛型类的对象
        MyGenerics<String> stringMyGenerics = new MyGenerics<>();
        //2.调用setter方法设置值
        stringMyGenerics.setNum(100);
        stringMyGenerics.setT("hello world"); // 也是正常的调用
        //3.调用toString方法查看对象属性的值
        System.out.println(stringMyGenerics);
    }
}
# 运行结果 : 就像使用一个正常类一样
MyGenerics{num=100, t=hello world}

3.泛型类的使用注意事项

  • 泛型类在使用时如果没有指定泛型的类型,则默认是 Object类型
  • 泛型的类型参数,只能传入 类类型,不可以传入基本数据类型
  • 同一个泛型类的运行时类型都是同一个
/**
 * author : northcastle
 * createTime:2021/10/18
 * 使用自定义的泛型类
 */
public class Application {
    public static void main(String[] args) {
     
        //1.未指明泛型类型时默认是 Object类型
        MyGenerics objectMyGenerics = new MyGenerics<>();
        Object t = objectMyGenerics.getT(); // 类型是Object

        //2.不可传入基本数据类型 : 编译时会报错
        //MyGenerics<int> myGenerics = new MyGenerics<int>();

        //3.运行时类型都是一致的
        MyGenerics<Boolean> booleanMyGenerics = new MyGenerics<>();
        MyGenerics<Integer> integerMyGenerics = new MyGenerics<>();
        System.out.println(booleanMyGenerics.getClass());
        System.out.println(integerMyGenerics.getClass());
        System.out.println(booleanMyGenerics.getClass() == integerMyGenerics.getClass());

    }
}
# 运行结果:
class com.northcastle.genericsclass.MyGenerics
class com.northcastle.genericsclass.MyGenerics
true

4.完成

Congratulations!
You are one step closer to success!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值