java.util.ConcurrentModificationException & iteration?

前端 未结 3 931
孤独总比滥情好
孤独总比滥情好 2021-01-25 22:28

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:

         


        
相关标签:
3条回答
  • 2021-01-25 23:17

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

    }

    0 讨论(0)
  • 2021-01-25 23:26

    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.

    0 讨论(0)
  • 2021-01-25 23:29

    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

    0 讨论(0)
提交回复
热议问题