Created
July 30, 2015 03:01
-
-
Save zzt93/e9c36315e7ebe475dce5 to your computer and use it in GitHub Desktop.
Getting Iterator first then modify container
will invalidate the iterator and cause `java.util.ConcurrentModificationException` for `next()` and `remove()` but not `hasNext()`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package so_test; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
/** | |
* Created by zzt on 7/30/15. | |
* <p> | |
* Description: | |
* Getting Iterator first then modify container will | |
* invalidate the iterator and cause `java.util.ConcurrentModificationException` | |
* for `next()` and `remove()` but not `hasNext()` | |
*/ | |
public class Iter { | |
public static void main(String[] args) { | |
add(); | |
remove(); | |
} | |
private static void remove() { | |
ArrayList<Integer> arrayList = new ArrayList<>(); | |
arrayList.add(1); | |
Iterator<Integer> iterator = arrayList.iterator(); | |
arrayList.remove(0); | |
System.out.println(iterator.hasNext()); | |
System.out.println(iterator.next()); | |
} | |
private static void add() { | |
ArrayList<Integer> arrayList = new ArrayList<>(); | |
arrayList.add(1); | |
Iterator<Integer> iterator = arrayList.iterator(); | |
// iterator.next(); | |
arrayList.add(2); | |
// iterator.remove(); | |
System.out.println(iterator.hasNext()); | |
// System.out.println(iterator.next()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment