theShadow89 theShadow89 - 1 month ago 8
Java Question

Java create map of Generic Objects

I have a Node class:

public class Node<T extends MySuperClass> {

private T data;
private Node<? extends MySuperClass> parent;
private List<Node<? extends MySuperClass>> children;

public Node(T data, Node<? extends MySuperClass> parent, List<Node<? extends MySuperClass>> children) {
this.data = data;
this.parent = parent;
this.children = children;
}

public T getData() {
return data;
}

public Node<? extends MySuperClass> getParent() {
return parent;
}

public List<Node<? extends MySuperClass>> getChildren() {
return children;
}

public void setData(T data) {
this.data = data;
}

public void setParent(Node<? extends MySuperClass> parent) {
this.parent = parent;
}

public void setChildren(List<Node<? extends MySuperClass>> children) {
this.children = children;
}
}


I need to create a map of Generic Node defined above. I have to write something like this

List<Map<Long, Node<? extends MySuperClass>>> tree = new ArrayList<Map<Long, Node< extends MySuperClass>>>();


When I try to add an instance of map to the list

public MyClass extends MySuperClass{

}

Map<Long, Node<MyClass>> myMap = new HashMap<Long,Node<MyClass>>();

tree.add(myMap);


The Compiler gives me the following message:

The method add(Map<Long,Node<? extends MySuperClass>>) in the type List<Map<Long,Node<? extends MySuperClass>>> is not applicable for the arguments (Map<Long,Node<MyClass>>)


Syntactically it is correct. I Can't understand why it doesn't work.

Answer

Your Map should be defined the same type as your List.

This is because the List expects a type of Map<Long, Node<? extends MySuperClass>>. The type Node<? extends MySuperClass> and Node<MyClass> are not the same.

From http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

Note: Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no relationship to MyClass<B>, regardless of whether or not A and B are related. The common parent of MyClass<A> and MyClass<B> is Object.

Note : I add to add a default constructor to your Node class to get the next four lines to compile since I didnt want to type in the params for the other constructor.

List<Map<Long, Node<? extends MySuperClass>>> tree = new ArrayList<Map<Long, Node<? extends MySuperClass>>>();
Map<Long, Node<? extends MySuperClass>> myMap = new HashMap<Long, Node<? extends MySuperClass>>();
myMap.put(1L, new Node<MyClass>());
tree.add(myMap);