[英]Why is addLast() in Java replacing my linked list?
I have a class that is supposed to create a hash table with a linked list for the values. 我有一个类,该类应使用值的链接列表创建哈希表。 If the key is new, it creates a linked list, and if it already exists it is supposed to append it to the end of the list.
如果密钥是新密钥,它将创建一个链接列表,如果该密钥已经存在,则应将其追加到列表末尾。 For some reason, when I use addLast() it is replacing the contents of my list.
出于某种原因,当我使用addLast()时,它将替换列表中的内容。 Can you see what I am doing wrong?
你能看到我做错了吗? Here is my code.
这是我的代码。 Thank you!
谢谢!
import java.util.*;
public class Semantic {
String currentScope;
Stack theStack = new Stack();
HashMap<String, LinkedList> SymbolTable= new HashMap<String, LinkedList>();
public boolean insertSymbol(String key, SymbolTableItem value){
LinkedList<SymbolTableItem> temp = new LinkedList<SymbolTableItem>();
SymbolTableItem obj;
if(!isContained(SymbolTable.get(key), value)){
if(SymbolTable.get(key) != null){
temp = SymbolTable.get(key);
}
temp.addLast(value);
SymbolTable.put(key, temp);
return true;
}
return false;
}
public boolean isContained(LinkedList list, SymbolTableItem obj){
if(list == null) return false;
while(!list.isEmpty()){
SymbolTableItem item;
item = (SymbolTableItem) list.removeFirst();
if(item.equals(obj))
return true;
}
return false;
}
public String printValues(){
return SymbolTable.toString();
}
public boolean isBoolean(){
return true;
}
public boolean isTypeMatching(){
return true;
}
public void stackPush(String theString){
theStack.add(theString);
}
}
The method isContained
removes every element up to and including the search element SymbolTableItem
obj
. 方法
isContained
移除直到搜索元素SymbolTableItem
obj
为止的每个元素。
If obj
occurs last in the LinkedList
then everything will be removed. 如果
obj
出现在LinkedList
最后,则所有内容都将被删除。
Check around item = (SymbolTableItem) list.removeFirst(); 检查项目=(SymbolTableItem)list.removeFirst();
The isContained method looks messed up. isContained方法看起来很混乱。
It looks like you're creating a new linked list before you test whether the value is new or not. 在测试值是否为新值之前,您似乎正在创建新的链接列表。 Try not creating the linked list until after you've tried to retrieve that value.
尝试检索该值之前,请不要创建链接列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.