1

Nodes are, for example, of type A, B and C.

Each of these nodes are different number of children. A can have 2 children, B can have 3 children and so on. Now, whether A will have a reference to B or C is not known a priori.

How do I do this for n nodes where each node is an object of a different class and can have a reference to any of the n-1 nodes?

user3266901
  • 293
  • 1
  • 2
  • 8

1 Answers1

1

You can create a Node class and pass the limit for the child nodes in the constructor.

class Node implements iNode
{
  private List<iNode> childNodes;
  private int maxChildren;
  ...

  public Node(int maxChildren)
  {
    this.maxChildren = maxChildren;
    this.childNodes = new ArrayList<iNode>();
  }

  public void addChildNode(iNode child) throws SomeCustomException
  {
    if (childNodes.size() < maxChildren) {
      childNodes.add(child);
    } else {
      throw new SomeCustomException();
    }
  }
}
indivisible
  • 4,892
  • 4
  • 31
  • 50
  • `Node` can have a reference to different types of nodes, and which node exactly is not known before the `Node` object has been created. That is my main concern! – user3266901 Feb 28 '14 at 06:29
  • Node was just a generic name I chose. If all the classes you want to use in the tree implements a shared interface then you can add them as children. – indivisible Feb 28 '14 at 06:34