如何确保泛型类型

时间:2018-02-10 19:54:49

标签: java generics

public class MyList<E> {

}

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

2 个答案:

答案 0 :(得分:1)

为整数创建MyList对象时,请执行以下操作:

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

我在评论中看到,您想为类型GameObject创建它,您可以采用相同的方式:

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

答案 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.