我有一個 Node 類,我希望每個 Node 都有一個葉子串列。為此,我創建了一個實體變數 ArrayList()。當我嘗試將節點添加到此串列時,我收到 NullPointerException:無法呼叫“java.util.ArrayList.add(Object)”,因為“this.nextSibling”為空。為什么會這樣?
這是我的代碼:
public class Node {
private String name;
private Node firstChild;
private ArrayList<Node> nextSibling;
Node (String n, Node d, ArrayList<Node> r) {
this.name = n;
this.firstChild = d;
this.nextSibling = r;
}
Node() {
this("", null, null);
}
Node (String s) {
this(s, null, null);
}
Node (String s, Node p) {
this(s, p, null);
}
Node(String s, ArrayList<Node> lst) {
this(s, null, lst);
}
public void setFirstChild (Node d) {
firstChild = d;
}
public void addNextSibling (Node r) {
nextSibling.add(r);
}
public static Node parsePostfix (String s) {
if (checkForNoData(s)) {
throw new RuntimeException("Invalid input: " s);
}
Stack<Node> nodeStack = new Stack<>();
List<String> nodeNamesCheck = new ArrayList<>();
List<String> nodeNames = getNodeNames(s);
int y = nodeNames.size() - 1;
Node root = new Node(nodeNames.get(y));
nodeStack.push(root);
nodeNamesCheck.add(nodeNames.get(y));
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')') {
y--;
Node firstChild = new Node(nodeNames.get(y), new ArrayList<>());
nodeNamesCheck.add(nodeNames.get(y));
nodeStack.peek().setFirstChild(firstChild);
nodeStack.push(firstChild);
} if (s.charAt(i) == ',') {
if (!nodeStack.empty())
nodeStack.pop();
y--;
Node nextSibling = new Node(nodeNames.get(y), new ArrayList<>());
nodeNamesCheck.add(nodeNames.get(y));
nodeStack.peek().addNextSibling(nextSibling);
nodeStack.push(nextSibling);
} else if (s.charAt(i) == '(') {
if (!nodeStack.empty()) {
nodeStack.pop();
}
}
}
if (nodeNames.size() != nodeNamesCheck.size() && nodeNames.size() != 1)
throw new RuntimeException("Invalid input: " s);
return root;
}
}
parsePostfix(String s) 方法將樹作為字串并使用節點重新創建它。示例輸入是“(H,G,F)E,(D,C,)B)A”。
uj5u.com熱心網友回復:
private ArrayList<Node> nextSibling;
Node (String n, Node d, ArrayList<Node> r) {
this.name = n;
this.firstChild = d;
this.nextSibling = r;
}
Node() {
this("", null, null);
}
Node (String s) {
this(s, null, null);
}
Node (String s, Node p) {
this(s, p, null);
}
您非常明確地設定nextSibling為null最后三個建構式。所以當然this.nextSibling是空的。
如果您不希望發生這種情況,則需要將其設定為 null 以外的值,例如new ArrayList<>().
(正如@trincot 所提到的,您的變數名稱也似乎令人困惑,nextSibling葉子串列的奇怪名稱也是如此 - 這將是孩子,而不是兄弟姐妹。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/524128.html
標籤:爪哇树
上一篇:Scala類擴展了Java類
下一篇:在物件中呼叫物件?
