Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a tree of objects in Java?

Tags:

java

tree

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
like image 778
Anderson Green Avatar asked Jan 22 '26 01:01

Anderson Green


2 Answers

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:

  • Go to the nth child of the current node, where n is the next value in your path.
  • If the child doesn't exist, create it.
  • Repeat until the end of the path is reached.
  • Return the current value (optional)
  • Set the value to the new value.

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.

like image 45
oconnor0 Avatar answered Jan 23 '26 16:01

oconnor0