[英]Storing Equations in a Java Tree Structure
I want to be able to store equations/algorithms in a java tree structure, so that I can easily retrieve and manipulate certain nodes. 我希望能够在Java树形结构中存储方程式/算法,以便可以轻松地检索和操作某些节点。
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):
由于树仅仅是从根节点来的节点网络,因此我创建了一个类Node,它可以具有一个,两个或三个子级(一个子级用于trig运算,两个子级用于算术运算,三个子级用于三元逻辑):
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 '+': 我不太擅长泛型类型,但是说我想存储“ 5 + 5”,我为“ +”创建一个根节点:
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<?>>();
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: 并且Node类的声明将开始:
public class Node<T,V> {
private T data;
List<Node<V>> nodeChildren = new ArrayList<Node<V>>();
// ...
public void addChild(Node<V> child) // etc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.