1 package day2_18;
2
3 import org.junit.Test;
4
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Iterator;
8
9 /**
10 *
11 集合元素的遍历操作:使用迭代器Iterator接口
12 1.内部的方法:hasNext() 和 next()
13 2.集合对象每次调用iterator(),都会得到一个新的迭代器对象,
14 默认游标都在集合的第一个元素之前
15
16 3.迭代器的默认方法remove():删除集合元素。
17 注意:> 它是遍历过程中通过迭代对象的remove()删除集合中的元素,不是集合对象的remove();
18 > 如果还未调用next(),此时指针没有指向任何元素,就调用remove(),报错IllegalStateException
19 如果调用next()后,调用remove(),已经将指针指向的元素删除了,再调用remove(),就会报错IllegalStateException
20
21
22 *
23 * @Author Tianhao
24 * @create 2021-02-18-15:47
25 */
26 public class IteratorTest {
27 @Test
28 public void test() {
29 Collection coll = new ArrayList();
30 coll.add(123);
31 coll.add(456);
32 coll.add(false);
33 coll.add(new String("Tom"));
34 coll.add(new Person("张三", 23));
35
36 //遍历操作
37 //推荐方式一:
38 //此时iterator指针在集合第一个元素的上面
39 // Iterator iterator = coll.iterator();
40 // //hasNext():判断iterator指针下面的元素是否存在
41 // while (iterator.hasNext()) {
42 // //存在,next():①指针下移 ②将指针指向的元素返回
43 // System.out.println(iterator.next());
44 // }
45
46 //推荐方式二:foreach ---> jdk5新增,用于遍历集合和数组
47 //底层仍然调用的是迭代器
48 for (Object obj : coll) {
49 System.out.println(obj);
50 }
51
52 }
53
54 @Test
55 public void test2() {
56 Collection coll = new ArrayList();
57 coll.add(123);
58 coll.add(456);
59 coll.add(false);
60 coll.add(new String("Tom"));
61 coll.add(new Person("张三", 23));
62
63 //错误迭代方式一
64 // Iterator iterator = coll.iterator();
65 // while (iterator.next() != null) {
66 // System.out.println(iterator.next());
67 // }
68
69 //错误迭代方式二
70 //死循环:不停的输出第一个元素 123
71 while (coll.iterator().hasNext()) {
72 System.out.println(coll.iterator().next());
73 }
74
75 }
76
77
78 @Test
79 public void test3() {
80 Collection coll = new ArrayList();
81 coll.add(123);
82 coll.add(456);
83 coll.add(false);
84 coll.add(new String("Tom"));
85 coll.add(new Person("张三", 23));
86
87 Iterator iterator = coll.iterator();
88 while (iterator.hasNext()) {
89 //还未调用next(),此时指针没有指向任何元素,就调用remove(),报错IllegalStateException
90 //iterator.remove();
91 Object next = iterator.next();
92 //如果指针指向的元素和 "Tom"内容相同
93 if ("Tom".equals(next)) {
94 //删除指针指向的元素
95 iterator.remove();
96 //调用next()后,调用remove(),再调用remove(),就会报错IllegalStateException
97 //iterator.remove();
98 }
99 }
100
101 //因为上面的iterator迭代器已经指向了集合元素的最后位置
102 // 所以再遍历集合元素,需要重新创建一个新的迭代器
103 iterator = coll.iterator();
104 while (iterator.hasNext()) {
105 System.out.println(iterator.next());
106 }
107 }
108
109 @Test
110 public void test4() {
111 String[] arr = new String[]{"MM","MM","MM"};
112
113 //方式一:普通for循环遍历
114 // for (int i = 0; i < arr.length; i++) {
115 // arr[i] = "GG";//改变arr数组
116 // }
117
118 //方式二:foreach循环遍历
119 for (String s : arr) {
120 s = "GG";//不会改变arr数组
121 }
122
123 for (int i = 0; i < arr.length; i++) {
124 System.out.println(arr[i]);
125 }
126 }
127
128 }