0

I want to compare the first element of list with all the consecutive elements and increment the first character and then compare again.

if elements have the same character then i remove the second occurance of the element

al =["a1","a","1a","ab"]

a1 and 1a have the same characters and i want to remove 1a


a1 = ["a1","a","ab"]

This is the code i've written to iter through the elements


while(iter.hasNext()){
        current = iter.next();
      while(iter.hasNext())
      {
        String next = iter.next();
        if(check(current,next))
          a.remove(next);
        }
      }

On implementing this i get this error

Exception in thread "main"  
        java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
        at java.util.ArrayList$Itr.next(Unknown Source)
        at anasub.ana(anasub.java:51)
        at anasub.main(anasub.java:81)

I tried using a for loop but when i remove the element inside the loop I get ArrayIndexOutOfBound exception.

Please review this code or provide an alternate solution.

Abal
  • 113
  • 11
  • 2
    Does this answer your question? [Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – OH GOD SPIDERS Feb 07 '20 at 10:29
  • please go through the question before marking it duplicate – Abal Feb 07 '20 at 10:35
  • 1
    What makes you think this isn't a duplicate? You want to remove something from a Collection while looping over it, and the marked duplicate is exactly about that and has multiple solutions. – OH GOD SPIDERS Feb 07 '20 at 10:38
  • how do i implement a nested loop using iterator. – Abal Feb 07 '20 at 10:41
  • 1
    The nesting is irrelevant. The answer is the same as for any other question of this kind. Do not call `remove` on the collection you’re iterating over, but use the `Iterator`, i.e. instead of `a.remove(next);` use `iter.remove()`. This will remove the last returned element, which is `next`, as the last thing you did with the iterator before your remove operation is `String next = iter.next();`. And since the inner loop will consume all elements, you could replace the outer loop with an `if(iter.hasNext())` anyway. – Holger Feb 07 '20 at 18:01

0 Answers0