Iterator遍历 (遍历集合)

迭代器(Iterator)

  迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。

  Java中的Iterator功能比较简单,并且只能单向移动:

  (1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

  (2) 使用next()获得序列中的下一个元素。

  (3) 使用hasNext()检查序列中是否还有元素。

  (4) 使用remove()将迭代器新返回的元素删除。

  Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。

迭代器应用:

 list l = new ArrayList();
 l.add("aa");
 l.add("bb");
 l.add("cc");
 for (Iterator iter = l.iterator(); iter.hasNext();) {
  String str = (String)iter.next();
  System.out.println(str);
 }
 /*迭代器用于while循环
 Iterator iter = l.iterator();
 while(iter.hasNext()){
  String str = (String) iter.next();
  System.out.println(str);
 }
 */

 

  

 

========================================================================

使用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, returns  true if  next() 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的顺序。

 

转载于:https://www.cnblogs.com/AceIsSunshineRain/p/5058373.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值