Search code examples
javaarraylistiteratorillegalstateexception

Java nested Iterator throws IllegalStateException


I have four different ArrayLists. I want to try out every possible combination of values.

If the first combination doesn't result in something that fulfills my constraints, I want to remove the first value from the first list and do the whole thing again with the next value.

I made an Iterator for each ArrayList but when I remove a value from the first ArrayList, it throws an IllegalStateException.

This is my code:

public static boolean revise(Haus haus1, Haus haus2) {
    boolean removed = false;

    Iterator<String> iteratorFarbe1 = haus1.getFarbListe().iterator();
    while (iteratorFarbe1.hasNext()) {
        String farbe1 = iteratorFarbe1.next();

        Iterator<String> iteratorFarbe2 = haus2.getFarbListe().iterator();
        while (iteratorFarbe2.hasNext()) {
            String farbe2 = iteratorFarbe2.next();

            Iterator<String> iteratorLand1 = haus1.getLandListe().iterator();
            while (iteratorLand1.hasNext()) {
                String land1 = iteratorLand1.next();

                Iterator<String> iteratorLand2 = haus2.getLandListe().iterator();
                while (iteratorLand2.hasNext()) {
                    String land2 = iteratorLand2.next();

                    Haus checkHaus1 = new Haus(haus1.getNummer(), farbe1, land1);
                    Haus checkHaus2 = new Haus(haus2.getNummer(), farbe2, land2);

                    if (!checkConstraints(checkHaus1, checkHaus2)) {
                        iteratorFarbe1.remove();
                        removed = true;
                    }
                }
            }
        }
    }
    return removed;
}

Solution

  • This could happen because teratorFarbe1.remove() called more than once between two calls of iteratorFarbe1.hasNext()