简体   繁体   中英

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". What is the code which creates a List of Instance of Type nodesClass?

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.

Instead of this you can go for 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.

But here the problem is you can not add any new objects to nodes variable ie

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.

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> will only make your empty list unusable - you won't be able to add anything to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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