gpt4 book ai didi

java-使用set时如何避免并发和其他错误-hashmap

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:14 25 4
gpt4 key购买 nike

我使用以下代码来迭代 HashMap - HashMap 变量的名称='context'

            Iterator iter = context.keySet().iterator();

while(iter.hasNext())
{
String keystring = (String)iter.next();
String varname= keystring.substring(0, keystring.indexOf("~"));
String level= keystring.substring(keystring.indexOf("~")+1);
Integer levelno= Integer.parseInt(level);

if(levelno==curr_level+1)
{
iter.remove();
//we have found a variable of current level... this has to be removed from hashmap...
//context.remove(keystring);
//also the same variable has to be removed from the script engine as well...
scriptEngine.removeVariable(varname);

}

}

上面的代码是否正确,尤其是从 HashMap 中删除数据?因为当我运行程序时,在 HashMap 中的不同(随机)值处会生成一条错误消息,指出无法找到特定值(在 HashMap 中)(该代码是单独的并与上述代码结合使用)。引用上面的代码,为了避免从 HashMap 中删除数据时出现错误,我必须记住什么?

最佳答案

是的,这是在不破坏迭代器的情况下删除值的正确方法。

但是,这并不意味着整个应用程序中不会出现逻辑错误,除了已经显示的代码之外。

关于java-使用set时如何避免并发和其他错误-hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com