1.什么是迭代器
迭代器:就是提供一种方法对一个容器对象中的各个元素进行访问,而又不暴露该对象容器的内部细节
2.为什么使用迭代器
因为java中不同的容器内部结构不一样,很多时候我们不知道怎么去遍历一个容器中的元素,为了使对容器内元素的操作更为简单,Java引入了迭代器模式。也就是把访问逻辑从不同类型的集合类中抽取出来,从而避免向外部暴露集合的内部结构。
3.使用方法
1 Iterator <类型> 迭代器名 = 集合名.iterator(); 2 while(迭代器名.hasNext()) 3 { 4 语句 5 }
举例说明
1 @Test 2 public void test1(){ 3 4 List<String> list = new ArrayList<>(); 5 list.add("1"); 6 list.add("2"); 7 list.add("3"); 8 list.add("4"); 9 list.add("5"); 10 11 Iterator<String> it = list.iterator(); 12 while(it.hasNext()){ 13 String str = it.next(); 14 System.out.print(str+" "); 15 } 16 System.out.println(); 17 for(String s : list){ 18 System.out.print(s + " "); 19 } 20 } 21 22 @Test 23 public void test2(){ 24 25 Map<Integer, String> m = new LinkedHashMap<>(); 26 m.put(1, "one"); 27 m.put(2, "two"); 28 m.put(3, "three"); 29 30 //传统迭代 entryset 31 Set<Map.Entry<Integer, String>> set = m.entrySet(); 32 Iterator<Map.Entry<Integer, String>> it = set.iterator(); 33 while(it.hasNext()){ 34 Map.Entry<Integer, String> me = it.next(); 35 int key = me.getKey(); 36 String value = me.getValue(); 37 System.out.println(key + "=" + value); 38 } 39 System.out.println(); 40 //用增强for来迭代 41 for(Map.Entry<Integer, String> entry : m.entrySet()){ 42 int key = entry.getKey(); 43 String value = entry.getValue(); 44 System.out.println(key + "=" + value); 45 } 46 }
4.使用迭代器时候需要注意的
- 迭代器不支持替换和添加新元素
- 要保证在使用Iterator遍历集合的时候不出错误,就应该保证在遍历集合的过程中不会对集合产生结构上的修改。
- 要注意remove的使用(下面给出例子)
public class Demo4 { //官方解释remove()方法: //从底层集合中移除此迭代器返回的最后一个元素,每次调用next()时,只能使用此方法一次 //如果迭代正在进行中使用除此方法以外的方法修改基础集合,则迭代器就会被破坏从而停止运行 @Test public void test1(){ List<String> all = new ArrayList<String>(); all.add("1"); all.add("2"); all.add("3"); Iterator<String> i1 = all.iterator(); while(i1.hasNext()){ String str = i1.next(); if("2".equals(str)){ all.remove(str); }else{ System.out.print(str + " "); } } System.out.println(); System.out.println(all); } @Test public void test2(){ List<String> all = new ArrayList<String>(); all.add("1"); all.add("2"); all.add("3"); Iterator<String> i1 = all.iterator(); while(i1.hasNext()){ String str = i1.next(); if("2".equals(str)){ i1.remove(); }else{ System.out.print(str + " "); } } System.out.println(); System.out.println(all); } }
可以看到test1和test2中一个用了集合的remove方法一个用了迭代器的remove方法,都从底层集合中把“2”去掉,但是test1调用集合remove方法后,迭代器就停止运行了,而test2调用迭代器的remove方法后,迭代器继续运行。所以我们要注意:如果使用除了迭代器remove方法外的方法对底层集合的结构进行了修改,那么就会使得迭代器被破坏从而停止运行!