I'm trying to implement a generic Tree.
Each Tree has a value
, a parent
and a list of its children
.
Children are added using following method:
public Tree<T> addChildren(Tree<T>... children) {
for (Tree<T> child: children) {
if (this.children.add(child)) {
child.setParent(this);
}
}
return this;
}
The problem begins when I have a List
of Trees I want to add as a children:
List<Tree<T>> newChildren;
Since there is no way to create array of parametrized type in Java, the most obvious solution is to iterate over list and add children one by one:
for (Tree<T> newChild: newChildren) {
myTree.addChildren(newChild);
}
But this is not an efficient use of varargs. Since I want to keep Tree
class as simple as possible, is there any other way to implement this ?
This can be easily solved by creating array of raw type:
Tree<String>[] newChildrenArray = new Tree[newChildren.size()];
newChildrenArray.toArray(newChildren);
myTree.addChildren(newChildrenArray);