【发布时间】:2017-09-24 05:28:30
【问题描述】:
在class Tree 我收到错误消息:
方法 removeparent() 未为 String 类型定义。
我想将字符串“Grandchild3”转换为 MyTreeNode 类实例的对象,然后我可以使用removep("Grandchild3") 调用像这样的方法Grandchild3.removeparent()。
我该怎么做?
这是 MyTreeNode 类:
public class MyTreeNode<T>{
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;
public MyTreeNode(T data) {
this.data = data;
}
public void addChild(MyTreeNode child) {
child.setParent(this);
this.children.add(child);
}
public void addChild(T data) {
MyTreeNode<T> newChild = new MyTreeNode<>(data);
newChild.setParent(this);
children.add(newChild);
}
public void addChildren(List<MyTreeNode> children) {
for(MyTreeNode t : children) {
t.setParent(this);
}
this.children.addAll(children);
}
public List<MyTreeNode> getChildren() {
return children;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
private void setParent(MyTreeNode parent) {
this.parent = parent;
}
public MyTreeNode getParent() {
return parent;
}
public void removeparent() {
this.parent = null;
}
public void removeChild(MyTreeNode<T> child)
{
this.children.remove(child);
}
}
这是类树:
public class Tree {
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
MyTreeNode<String> root = new MyTreeNode<>("Root");
MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");
MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");
root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");
root.addChildren(Arrays.asList(
new MyTreeNode<>("Child4"),
new MyTreeNode<>("Child5"),
new MyTreeNode<>("Child6")
));
for(MyTreeNode<String> node : root.getChildren()) {
System.out.println(node.getData());
}
printTree(root, " ");
removep("Grandchild3"); //error message"The method removeparent() is undefined for the type String"
printTree(root, " ");
}
private static void printTree(MyTreeNode<String> node, String appender) {
System.out.println(appender+node.getData());
for (MyTreeNode each : node.getChildren()){
printTree(each, appender + appender);
}
}
public static void removep(MyTreeNode<String> node)
{
node.getParent().removeChild(node);
node.removeparent();
}
}
【问题讨论】:
-
removep有一个MyTreeNode<String>类型的参数。您在removep("Grandchild3");行中将一个字符串传递给它。String与MyTreeNode<String>不同。 -
@TT 是的,这是我的问题。怎么弄出来的?
-
只是猜测:致电
removep(new MyTreeNode<>("Grandchild3"));? -
@TT 不起作用,因为这意味着你创建了一个新的,但不是我要删除的那个女巫。
-
嗯...
root.removeChild(new MyTreeNode<>("Grandchild3"));。但是,您在MyTreeNode类中缺少Object.equals实现。
标签: java string type-conversion