forked from eaglesky/JavaPractice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestListIterator.java
More file actions
47 lines (42 loc) · 1.36 KB
/
TestListIterator.java
File metadata and controls
47 lines (42 loc) · 1.36 KB
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
45
46
47
import java.util.*;
class TestListIterator {
public static void main(String[] args) {
List<Integer> l1 = new ArrayList<>();
l1.add(1);
l1.add(3);
l1.add(5);
l1.add(7);
l1.add(9);
ListIterator<Integer> iter = l1.listIterator();
System.out.println("Traversing the list in forward direction:");
while (iter.hasNext()) {
System.out.println(iter.nextIndex() + ": " + iter.next());
}
System.out.println("\nTraversing the list in backward direction:");
//If without previous iteration, we should create iter like this:
//iter = l1.listIterator(l1.size()), so that iter points to the position
//right after the last element.
while (iter.hasPrevious()){
System.out.println(iter.previousIndex() + ": " + iter.previous());
}
System.out.println("\nAdding an element while iterating: ");
while (iter.hasNext()) {
if (iter.nextIndex() == 2) {
iter.add(4);
}
System.out.println(iter.nextIndex() + ": " + iter.next());
}
System.out.println("After inserting 4 after the second element: " + l1);
System.out.println("\nRemoving an element while iterating: ");
iter = l1.listIterator();
while (iter.hasNext()) {
int id = iter.nextIndex();
int cur = iter.next();
if (cur == 4) {
iter.remove();
}
System.out.println(id + ": " + cur);
}
System.out.println("After removing 4 from the list: " + l1);
}
}