java - 哈希集迭代抛出非法状态错误

标签 java iterator hashmap hashtable hashset

我有两个散列映射,我需要从其中一个中删除一个元素。这就是我现在正在做的。

for(Iterator<Byte> iterator = Ka.iterator(); iterator.hasNext();) {
                byte kaValue = iterator.next();
                byte potentialPIValue = (byte)(E1a + kaValue);
                for(byte actualPIValue : getPIs) {                       
                    if (potentialPIValue != actualPIValue )                         
                        iterator.remove();
                }
            }   

但是我得到了这个错误,我看不出代码有什么问题。有人知道这里的问题是什么吗?

 exception in thread "main" java.lang.IllegalStateException
at java.util.HashMap$HashIterator.remove(HashMap.java:910)
at DESPrac.main(DESPrac.java:59)

最佳答案

您可能在没有移动到下一个元素的情况下点击了 iterator.remove() 语句两次,因为您是在内部循环中调用它。

尝试

       for(Iterator<Byte> iterator = Ka.iterator(); iterator.hasNext();) {
            byte kaValue = iterator.next();
            byte potentialPIValue = (byte)(E1a + kaValue);
            for(byte actualPIValue : getPIs) {                       
                if (potentialPIValue != actualPIValue ){                         
                    iterator.remove();
                    break; // Exit the inner loop
                }
            }
        }   

关于java - 哈希集迭代抛出非法状态错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20415133/

相关文章:

Java同步问题

c++ - Const 方法和自定义迭代器

java - 在 hashmap 中查找序列

java - hashmap中入口类中的hashcode和equals是什么

java - 如何快速获取图像矩阵? java

java - @ElementCollection 和字符串列表的异常

java - 在列表中查找特定记录并显示该记录上方的 5 条记录和下方的 5 条记录

c++ - QSet::find() 迭代器解引用出现 “cannot convert ‘this’ 指针”错误?

algorithm - 给定整数迭代器的正迭代器设计

html - 我们如何在 JSTL 中迭代 HashMap?