0

I'm so very new to Arraylists & iterators & this is the first time I got this exception. I have an ArrayList u & I'd like to do the following algorithm:

for (Character c:u){

    if(k==1){           //base case

        if(isAnswer(s+u.get(0)))

            System.out.println(s+u.get(0)+" is the correct sequence."+ '\n');
        return;
    }

    else{
        u.remove(c);
        puzzleSolve(k-1, s+c , u);
        u.add(c);
        removeLastChar(s);
    }

    } //end of for each

as I searched this exception a little bit i found out I can't remove iterms weth for each on a arraylist & I need to use iterator but i kinna got confused where & how exactly i must put the while(iter.hasNext()) & such stuff for this piece of code. i would be more than grateful if you could help me

PS. s is String ( initially empty) & k is int

1

3 Answers 3

1

Try this:

Iterator<Character> iter = u.iterator();
while (iter.hasNext())
{
    Character currentChar = iter.next();

    if(k==1){           //base case

        if(isAnswer(s+u.get(0)))

        System.out.println(s+u.get(0)+" is the correct sequence."+ '\n');
        return;
    }

    else{
         iter.remove();
         puzzleSolve(k-1, s+currentChar  , u);
         u.add(currentChar);
         removeLastChar(s);
    }

}

Sign up to request clarification or add additional context in comments.

4 Comments

thanks, i did yet it still throws the same exception at lines:
Character currentChar = iter.next();
and another line i have called the sovePuzzle method
It works fine for me...can you update your post with the exact stack trace you are getting?
1

how exactly i must put the while(iter.hasNext())

You can use iterator as below:

Iterator<Character> iter = u.iterator();
while(iter.hasNext())
{
  Character c = iter.next();
  .....
}

Initialize your list with generics: List<Character> u = new ArrayList<Character>();

Hint: use iter.remove(), iter.add() wherever applicable instead of u.remove() and u.add().

You need to start here: http://www.tutorialspoint.com/java/java_using_iterator.htm

2 Comments

& then my entire if else in between?!
Yes. Your code between it. It acts as a replacement for the enhanced for loop, in your code.
0

When you are using foreach loop, you are using iterator implicitly.

ConcurrentModificationException occurs when the collection is modified by "simultaneously" with the passage of an iterator over a collection by any means, except for the iterator.

So, use iterator

Iterator<Character> iter = u.iterator();
while (iter.hasNext())

in cases you need to modify collection in loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.