-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFailFastInteration.java
More file actions
44 lines (34 loc) · 1018 Bytes
/
Copy pathFailFastInteration.java
File metadata and controls
44 lines (34 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package interviewQuestions1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
* 1. Whereas Fail-fast iterators throw an
* exception(ConcurrentModificationException) if the collection is modified
* while iterating over it. 2. iterators traverse over the clone of the
* collection
*/
public class FailFastInteration {
public static void main(String[] args) {
List<Integer> integers = new ArrayList<Integer>();
integers.add(1);
integers.add(2);
integers.add(3);
for (Integer i : integers) {
//integers.remove(2); // ConcurrentModificationException
}
Iterator<Integer> itr = integers.iterator();
while (itr.hasNext()) {
Integer a = itr.next();
//itr.remove(); // will not throw Exception
//integers.remove(1); // .ConcurrentModificationException
// integers.add(4); //.ConcurrentModificationException
// itr.next(); //NoSuchElementException
}
while (itr.hasNext()) {
Integer a = itr.next();
System.out.println(a);
}
}
}