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

16,810

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.

Share:
16,810
Anderson Green
Author by

Anderson Green

I write source-to-source compilers in JavaScript using Peggyjs. I also write compilers in Prolog. For reference, I also have a list of source-to-source compilers on GitHub.

Updated on July 17, 2022

Comments

  • Anderson Green
    Anderson Green almost 2 years

    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
    
  • Anderson Green
    Anderson Green over 12 years
    This isn't homework; it's part of a fractal generator that I'm creating for a game. I want the fractal to be represented by a tree data structure, since using nested arrays is too cumbersome.
  • Anderson Green
    Anderson Green over 12 years
    I basically want the tree to act like an array with an infinite number of dimensions, and I want to create "getter" and "setter" methods for the tree. So if the statement add("Hi!", 0) were executed, then something get(0) should return the string "Hi!". Then, the statement set(1, 0, 0) would add the integer 1 as the 0th leaf of the node (0).