【发布时间】:2021-06-27 20:42:11
【问题描述】:
我有一个方法可以在具有特定 id 的链表中找到一个节点并将项目添加到该节点的数组列表中。
ArrayList <String> elems;
public Place addElemToLst(String id, String elem) {
// if no nodes create new node
if (head == null) {
Node node = new Node(id);
node.elems.add(item);
head = unit;
} else if (head != null) {
Node curr = head;
while (curr.next != null && !curr.next.id.equals(id)) {
curr = curr.next;
}
// if there is a id match
if (curr.id.equals(id)) {
curr.elems.add(item);
}
// add new Node
else { // the error is in this section
Node node = new Node(id);
node.elems.add(elem);
curr.next = node;
}
}
return this;
}
问题是当我在一个 ID 上多次调用 addElemToLst() 并说“item1”并继续向 arraylist 添加元素时,arraylist 只会保留最后一个输入到 arraylist 中的项目。本质上,arraylist 的大小始终为 1,因为以前的条目不断被替换。为什么会这样,错误是什么?我已将错误与代码中的注释隔离开来。 谢谢
【问题讨论】:
-
可以添加缺少的代码吗?
-
item在哪里定义?由于您没有在您的方法中创建它,您可能会一次又一次地添加相同的对象item。但这通常会导致您多次看到包含相同元素的列表。 -
抱歉项目应该是 elem
-
与问题无关,但“else if (head != null)”检查是多余的。一个简单的“else”会更好。
标签: java