Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashset Iteration throws Illegate State error

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)
like image 328
CodeGeek123 Avatar asked Dec 06 '13 03:12

CodeGeek123


1 Answers

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
                }
            }
        }   
like image 106
Ren Avatar answered Nov 18 '22 04:11

Ren