Generics - Storing Equations in a Java Tree Structure

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I want to be able to store equations/algorithms in a java tree structure, so that I can easily retrieve and manipulate certain nodes.

To store the equations, I created three enum sets for Operations, Relations and Logical Operations:

private enum Operation {
    PLUS, MINUS, TIMES, DIVIDE, SIN, COS, TAN
}
private enum Relation {
    EQUALS, NOT_EQUALS, GREATER_THAN, GREATER_THAN_OR_EQ, LESS_THAN, LESS_THAN_OR_EQ
}
private enum LogicOperation {
    AND, OR, TERNARY
}

I want to create a tree structure that can hold any of these enum sets, or any value. Since a tree is simply a network of nodes coming from a root node, I created a class Node, which could have either one, two or three children (one child for trig operations, two for arithmetic operations, three for ternary logic):

public class Node<T> {

    private T data;
    List<Node<T>> nodeChildren = new ArrayList<Node<T>>();

    Node(T data) {
        this.data = data;
    }

    public void addChild(Node<T> child) {
        this.nodeChildren.add(child);
    }

    public void addChildren(Node<T> child1, Node<T> child2) {
        this.nodeChildren.add(child1);
        this.nodeChildren.add(child2);
    }

    public void addChildren(Node<T> child1, Node<T> child2, Node<T> child3) {
        this.nodeChildren.add(child1);
        this.nodeChildren.add(child2);
        this.nodeChildren.add(child3);
    }

    public T getData() {
        return this.data;
    }

    public List<Node<T>> getNodeChildren() {
        return this.nodeChildren;
    }
}

I m not great at generic types, but say I want to store 5 + 5 , I create a root node for the + :

Node<Operation> op = new Node(Operation.PLUS);

But then I get a type mismatch error when I try to add two children that are of type integer:

op.addChildren(new Node<Integer>(5), new Node<Integer>(5));

Could someone possibly point me in the right direction?

Thanks

    • EDIT **

The answer, for anyone interested is to use the generic type ?:

List<Node<?>> nodeChildren = new ArrayList<Node<?>>();

Answers

You need two type parameters, one for the operation type and one for the child type. So your sample line would read:

Node<Operation,Integer> op = new Node<>(Operation.PLUS);

and the declaration of the Node class would start:

public class Node<T,V> {

    private T data;
    List<Node<V>> nodeChildren = new ArrayList<Node<V>>();

    // ...

    public void addChild(Node<V> child) // etc

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/21769334/storing-equations-in-a-java-tree-structure

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils