有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何确保泛型类型的类型

public class MyList<E> {

}

在上面的示例中,如何确保在创建“MyList”对象时E属于某个类


共 (2) 个答案

  1. # 1 楼答案

    您可以尝试使用下面的泛型绑定

    class MyList<E extends YourClass> {
    
    }
    

    例如:

    class MyList<E extends Number> {
    }
    

    对于上面的示例,MyList只允许传递Number或其子类型(Integer, Double etc

    所以,如果您尝试创建如下所示的对象

    MyList<Integer> list = new MyList<>(); // This will works fine as Integer is subclass of Number.
    
    MyList<String> list = new MyList<>(); // This will give you compilation error as String is not a subclass of number.
    
  2. # 2 楼答案

    当您为例如整数创建MyList对象时,您可以执行以下操作:

    MyList<Integer> myList = new MyList<>();
    

    我在您的评论中看到,您希望为类型GameObject创建它,您可以用同样的方法:

    MyList<GameObject> myList = new MyList<>();