wcarhart
wcarhart

Reputation: 2773

How to make a tree with multiple Object types in Java?

I am trying to use a tree structure in Java, but I need it to hold different types in its data field. The format of my question is very similar to this this question, but I couldn't find an answer to my problem based on the answers to that question.

The following is my simple TreeNode class. I have only included the skeleton of my code.

public class TreeNode<Character> {
    public Character data;
    public TreeNode<Character> parent;
    public TreeNode<Character> leftChild;
    public TreeNode<Character> rightChild;

    // basic methods, code omitted for simplicity
    public TreeNode(Character data) {...}
    public TreeNode<Character> addLeftChild(Character data) {...}
    public TreeNode<Character> addRightChild(Character data) {...}
}

I have another custom class public class NFA, and I would like to be able to store data in my tree in the following fashion:

    root
  /      \
NFA     Character
       /        \
    Character   Character

and so on...

What can I change in the class to make it so the tree supports Character and NFA? Should I use public class TreeNode<Object> and then somehow cast Object as Character or NFA in every method?

I have seen other examples using an Iterator, but I after reading the Java docs I am still unsure of how to implement this.

For reference, here is a skeleton of NFA. Character is the generic java.lang.Character class.

public class NFA {
    public int numStates;
    public ArrayList<Character> alphabet;
    public ArrayList<Transition> transitionFunction;
    public int startState;
    public ArrayList<Integer> endStates;

    // constructors
}

Upvotes: 1

Views: 2577

Answers (2)

Glen Pierce
Glen Pierce

Reputation: 4801

Use of generics could solve this problem for you like so:

public class TreeNode<T Extends ClassThatIsACharacterAndAnNFA> {
    public T data;
    public TreeNode<T> parent;
    public TreeNode<T> leftChild;
    public TreeNode<T> rightChild;

    // basic methods, code omitted for simplicity
    public TreeNode(T data) {...}
    public TreeNode<T> addLeftChild(T data) {...}
    public TreeNode<T> addRightChild(T data) {...}
}

This obviously assumes that NFA and Character Extend from the same class, in this case: ClassThatIsACharacterAndAnNFA.

Upvotes: 0

ahmed eshra
ahmed eshra

Reputation: 79

I think it is better to create different types of nodes that implement TreeNode object

Example:

public class NFANode implements TreeNode {

}

public class charNode implements TreeNode {

}

And your tree has a relation to TreeNode only.

Upvotes: 3

Related Questions