2012-06-02 18 views
1

我使用下面的代碼通過HashMap的變量=「語境」Java的使用如何設置時避免併發和其他錯誤 - HashMap的

  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中刪除數據的問題?因爲當我運行程序時,然後在散列表中的不同(隨機)值處生成錯誤消息,該錯誤消息無法找到特定值(在散列映射中)(該代碼是分開的並與上述代碼結合使用)。 參考上面的代碼,我有什麼要記住,以避免從哈希映射中刪除數據時出錯?

+1

從多個線程使用'context'嗎? – Jeffrey

回答

1

是的,這是在不破壞迭代器的情況下刪除值的正確方法。

但是,這並不意味着在整個應用程序中不會出現邏輯錯誤,除了已經顯示的代碼之外。

相關問題