详解泛型类

65 阅读1分钟

1. 泛型类的声明语法

class 类名 <泛型标识,泛型标识…>{  
[private](https://so.csdn.net/so/search?q=private&spm=1001.2101.3001.7020) 泛型标识 属性名;  
…  
}

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. 在程序中使用泛型类

/**
 * 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