java如何确保泛型类型的类型 4 月,3 周 Questions & Answers 63 public class MyList<E> { } 在上面的示例中,如何确保在创建“MyList”对象时E属于某个类
# 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 楼答案 当您为例如整数创建MyList对象时,您可以执行以下操作: MyList<Integer> myList = new MyList<>(); 我在您的评论中看到,您希望为类型GameObject创建它,您可以用同样的方法: MyList<GameObject> myList = new MyList<>();
# 1 楼答案
您可以尝试使用下面的泛型绑定
例如:
对于上面的示例,MyList只允许传递
Number
或其子类型(Integer, Double etc
)所以,如果您尝试创建如下所示的对象
# 2 楼答案
当您为例如整数创建
MyList
对象时,您可以执行以下操作:我在您的评论中看到,您希望为类型
GameObject
创建它,您可以用同样的方法: