I would like to implement a generic TreeNode and a Generic Tree. I've seen few examples on stackoverflow and other places, but couldn't understand completely.
public interface Node<K, V>
{
K getId();
V getData();
K getParentId();
void addChild(Node<K, V> child);
List<Node<K, V>> getChildren();
}
public class Tree<K, V>
{
private Node<K, V> root;
public void loadData(Map<K, V> data)
{
// by figuring out the root node from map, populate tree
// root node is the one with parentId as null
// and the logic follows. Simple level order insertion
}
}
Although the above code servers my purpose, I want to understand if there is a better way to achieve this.
Like declare Tree as
public class Tree<T extends Node<?, ?>
{
private T root;
public void loadData(Map<K, V> data)
{
// by figuring out the root node from map, populate tree
// root node is the one with parentId as null
// and the logic follows. Simple level order insertion
}
}
In the above case, where should my data load method reside? Some Util class?
Basically, I want to understand the principles to be followed when creating Classes that are generic over types which in turn are generic.
Thanks.