Hashset Iteration throws Illegate State error

hashmap, hashset, hashtable, iterator, java

Solution

You're probably hitting the iterator.remove() statement twice without moving to the next element, since you're calling it in your interior loop.

Try

       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
                }
            }
        }   

Problem

I have two hash maps and I need to remove an element from one of them. This is what I am doing right now. ``` 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(); } } ``` However i get this error and I am unable to see what's wrong with the code. Would anyone know what the problem here is? ``` exception in thread "main" java.lang.IllegalStateException at java.util.HashMap$HashIterator.remove(HashMap.java:910) at DESPrac.main(DESPrac.java:59) ```

Original source