用Iterator实现遍历集合
来源:互联网 发布:酷炫js效果 编辑:程序博客网 时间:2024/05/22 03:06
使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码。
示例:
- Collection coll = new Vector(); //LinkedList(); //ArrayList();
- coll.add("Tody");
- coll.add("is");
- coll.add("Sunday.");
- // Output all elements by iterator
- Iterator it = coll.iterator();
- while(it.hasNext()) {
- System.out.print(it.next() + " ");
- }
输出:
Tody is Sunday.
1.hasNext()函数的API解释
boolean java.util.Iterator.hasNext()
hasNext
boolean hasNext()
- Returns
true
if the iteration has more elements. (In other words, returnstrue
ifnext()
would return an element rather than throwing an exception.)- Returns:
true
if the iteration has more elements
---------------------------------------------------------
2.next()函数的API解释
Object java.util.Iterator.next()
next
E next()
- Returns the next element in the iteration.
- Returns:
- the next element in the iteration
- Throws:
NoSuchElementException
- if the iteration has no more elements
- Collection coll = new HashSet();
- coll.add("Tody");
- coll.add("is");
- coll.add("Sunday.");
- // Output all elements by iterator
- Iterator it = coll.iterator();
- while(it.hasNext()) {
- System.out.print(it.next() + " ");
- }
输出:
is Sunday. Tody
由上面两个例子看出,在List和Set对象中,Iterator的next()方法返回的值是不一样的。
原因是List属于线性集合,元素是有序的,读取时是按照数组的形式,一个接一个的读取,存储也是按照add的顺序添加的。
而Set属于非线性的,是无序的,所以读取的元素与添加的顺序不一定一致。
对于HashSet,其实它返回的顺序是按Hashcode的顺序。
如果迭代也有序,则可以用LinkedHashSet。
http://topic.csdn.net/u/20101227/09/63a23d05-7f15-4b0e-9287-e97f96ba4349.html?77188351
0 0
- 用Iterator实现遍历集合
- 用Iterator实现遍历集合
- 用Iterator实现遍历集合
- 用Iterator实现遍历集合
- 用Iterator实现遍历集合
- 用Iterator模式实现遍历集合
- iterator遍历集合解析
- iterator 遍历集合
- Struts2 iterator遍历集合
- 集合遍历 Iterator Foreach
- Iterator遍历集合特点
- java集合遍历 Iterator理解
- s:iterator遍历对象集合
- Java Iterator遍历List集合
- Iterator迭代器遍历集合元素
- java-Iterator(迭代器)遍历集合
- java 集合遍历Iterator/foreach
- 用foreach和Iterator遍历集合的方法
- oracle 10g下范围分区扫描的几种方式
- Dreamweaver CS6破解教程[序列号+破解补丁]
- 黑马程序员_java多线程
- Chrome开发,debug的使用方法。
- 互联网金融-互联网金融分析框架:从支付、投资、融资三个维度理解何谓“互联网金融”
- 用Iterator实现遍历集合
- listView中adapter有不同的click事件的简单写法
- 记__零基础学java的开始
- “注释”部分补充知识点:
- 玩转C++运算符重载
- 手机屏幕分辨率说明大全 VGA - hd
- 枚举根节点
- hive中partition如何使用
- 核密度估计