0

Code :

ArrayList one = new ArrayList<>();

        for(int i=1; i<=80; i++){
            one.add(i);
            if(i==40){
                for(int j=21; j<=40; j++){
                    one.add(j);
                }
            }

        }

        ArrayList abc = new ArrayList<>(one);
        System.out.println(abc);
        for(int i=0; i<one.size(); i++){

            if(i==20){
                System.out.println(one.subList(i, i+20).size());
                List<Integer> bb = one.subList(i, i+20);
                System.out.println(bb);
                ListIterator<Integer> lt= bb.listIterator();
                while(lt.hasNext()){
                    int ind = one.indexOf(lt.next());
                    one.remove(ind);
                }
            }
        }

Am I facing this issue due to fail fast iterators? What is the solution to remove the set of numbers (20 to 40) from the main list? (Only the first occurrence)?

Mercenary
  • 2,106
  • 6
  • 34
  • 43
  • 1
    There are a lot of questions about this on this site... Just search a little. – jahroy Jun 04 '14 at 06:13
  • You cannot remove from a list while looping over it – Pphoenix Jun 04 '14 at 06:17
  • @Pphoenix You can, just not through the list itself – awksp Jun 04 '14 at 06:18
  • I do not think this is a duplicate! I'm using an Iterator but still I face the exception!!! – Mercenary Jun 04 '14 at 06:19
  • 2
    Modifying the list while iterating over it with an Iterator _is_ the problem. (And the sublist counts as the "main" list here, because the sublist is backed by the main list -- it's a view into the same data structure.) – yshavit Jun 04 '14 at 06:21
  • I suggest you read the linked questions (especially their answers) more carefully. You use iterators, yes, but not in the way that would allow you to do what you want to do. – awksp Jun 04 '14 at 06:22
  • Yes I got the point that we need to use `remove()` but in my scenario, I need to remove only the first occurrence of that element and that is why I used `removeFirstOccurrence` – Mercenary Jun 04 '14 at 06:25
  • 1
    Well obviously that isn't going to work. Having a particular need doesn't allow you to ignore the fact that structurally modifying a `List` invalidates any created iterators. Be flexible and change your code. – awksp Jun 04 '14 at 06:30
  • You need to do this in two phases. First, copy the `Integer`s into a `Set` (needs to be a set so that each int is only here once.) then iterate over that set, calling `removeFirstOccurence` on the list for each item. – yshavit Jun 04 '14 at 06:30
  • I've changed the code. What should I do here to avoid the exception. I'm using an `Iterator` and `remove`. I still get the exception. – Mercenary Jun 04 '14 at 11:19
  • Could someone please take a look at the code and find out why was the exception thrown? – Mercenary Jun 05 '14 at 06:35

0 Answers0