简体   繁体   English

通用类型的元素列表-Java

[英]List of elements of generic Type - Java

i am not able to handle some kind of structure, I have to work with: 我无法处理某种结构,我必须使用:

Class<? extends Node> nodesClass = gds.getNodeType();
List<nodesClass> nodes = new ArrayList();

Now eclipse doesn't accept "nodesClass". 现在,eclipse不接受“ nodesClass”。 What is the code which creates a List of Instance of Type nodesClass? 创建nodeType类型实例列表的代码是什么?

I think you are trying to get class type from the user by calling 我认为您正在尝试通过调用从用户获取类类型

Class<? extends Node> nodesClass = gds.getNodeType();

Then by using that class type given by the method gds.getNodeType() you want to create ArrayList object. 然后,通过使用方法gds.getNodeType()给出的类类型,您想要创建ArrayList对象。

Instead of this you can go for List<? extends Node> nodes = new ArrayList<>(); 除此之外,您可以使用List<? extends Node> nodes = new ArrayList<>(); List<? extends Node> nodes = new ArrayList<>(); so that to the nodes variable you can assign any ArrayList object with generic type that should be sub class to Node class. 因此,可以为nodes变量分配具有泛型类型的任何ArrayList对象,该对象应该是Node类的子类。

But here the problem is you can not add any new objects to nodes variable ie 但是这里的问题是你不能向nodes变量添加任何新对象,即

nodes.add(new Node()) is illegal, but you can type secure that you can have only List object that is having generic type sub class to Node class. nodes.add(new Node())是非法的,但是您可以键入secure,以使您只能拥有具有Node类的通用类型子类的List对象。

If this answer is not appropriate to you let me know what is your exact requirement 如果此答案不适合您,请告诉我您的确切要求是什么

The only way you can do something useful with the list you are trying to create is by creating it as: 您可以对要创建的列表执行有用的操作的唯一方法是将其创建为:

List<Node> nodes = new ArrayList();

Trying to create a list of List<? extends Node> 尝试创建List<? extends Node>List<? extends Node> List<? extends Node> will only make your empty list unusable - you won't be able to add anything to it. List<? extends Node>只会使您的空列表不可用-您将无法对其添加任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM