迭代器--遍历集合的专用工具

【不使用迭代器遍历集合】

 1 package com.hxl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Arrays;
 5 import java.util.Collection;
 6 
 7 public class Test {
 8 
 9     public static void main(String[] args) {
10         // 实例化一个集合对象
11         Collection c = new ArrayList<>();
12         // 添加元素
13         c.add(new Student("aa", 11, '男'));
14         c.add(new Student("bb", 22, '男'));
15         c.add(new Student("cc", 33, '女'));
16         c.add(new Student("dd", 44, '男'));
17         c.add(new Student("ee", 55, '女'));
18         // 将集合转为Object[]数组
19         Object[] objs = c.toArray();
20         // 遍历数组
21         for (int i = 0; i < objs.length; i++) {
22             // 这里Student类中的toString()方法已经重写过了
23             System.out.println(objs[i]);
24         }
25     }
26 }

【使用迭代器Iterator】

 

 1 package com.hxl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Arrays;
 5 import java.util.Collection;
 6 import java.util.Iterator;
 7 
 8 public class Test {
 9 
10     public static void main(String[] args) {
11         // 实例化一个集合对象
12         Collection c = new ArrayList<>();
13         // 添加元素
14         c.add(new Student("aa", 11, '男'));
15         c.add(new Student("bb", 22, '男'));
16         c.add(new Student("cc", 33, '女'));
17         c.add(new Student("dd", 44, '男'));
18         c.add(new Student("ee", 55, '女'));
19         // 使用迭代器有两种方法,方法一:while循环遍历,优点逻辑结构清晰
20         // 实例化迭代器Iterator对象,注意Iterator是接口,这里是其实现类的对象.
21         Iterator it = c.iterator();
22         while (it.hasNext()) {
23             // it.next()方法返回的是Object对象,而它其实是Student对象,并且重写了toString方法。
24             System.out.println(it.next());
25         }
26         
27         // 方法二:for循环遍历迭代器,优点节省内存空间,缺点逻辑结构不那么清晰
28         /*
29             for (Iterator it = c.iterator(); it.hasNext();不需要写表达式) {
30                 System.out.println(it.next()); 
31             }
32         */
33     }
34 }

 

posted @ 2018-02-16 13:59  Schiller_Hu  阅读(227)  评论(0编辑  收藏  举报