I am trying to create a tree of Objects in Java. I also want to use a Java class that makes it easy to add or remove nodes from the tree. What would be the best class to use for this purpose?
Example: Here is an array of objects. The object at the top of the array is the string "world". The leaves are integers here, and I want to add the string "This is at (world, 0, 0)!" as a leaf at "(world, 0, 0)". What Java class would be best for this purpose?
"world"
/\
0 1
/ \ /\
0 1 0 1
Make your own. It's easy. Super super easy:
public class Tree{
public Node root;
}
public class Node{
public ArrayList<Node> children;
public Node parent;
public String value;
}
Now, putting a string value with a sequence of integers would be done something like this:
public class Tree{
public String put(String value, int[] path){
Node current = root;
for(int i=0;i<path.length;i++){
if(current.children.get(i)==null){
current.children.add(i, new Node());
}
current = current.children.get(i);
}
String ret = current.value;
current.value = value;
}
}
Getting the value would be similar, except that you wouldn't overwrite the current value with a given value.
A description of what put does in English:
So using this would look something like this:
Tree myTree = new Tree();
myTree.root = new Node();
int[] path = {0, 0, 0};
myTree.put("hi", path);
System.out.println(myTree.get(path));
And you'll get "hi" in your console.
This sounds vaguely like homework. Is it? It's usually better to be up front about it if it is.
There's not really a data structure in Java that will do what you want, since it seems like you're interested in direct tree manipulation. The Java collections are more about the abstract data type provided (List, Set, Map) than the specifics of the backing implementation; the differing implementations are provided for their different performance characteristics.
In summary, you're probably best off writing your own. Unless all you really care about is mapping from one key to a value, then any of the Map implementations will do well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With