用Iterator实现遍历集合

hasnext() 与next() 函数的api解释




1.List对象中next()的使用

使用Collection类的Iterator,可以方便的遍历Vector, ArrayList, LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码。

示例:

  1. Collection coll = new Vector(); //LinkedList(); //ArrayList();  
  2. coll.add("Tody");  
  3. coll.add("is");  
  4. coll.add("Sunday.");  
  5.   
  6. // Output all elements by iterator  
  7. Iterator it = coll.iterator();  
  8. while(it.hasNext()) {  
  9.     System.out.print(it.next() + " ");  
  10. }  

输出:

Tody is Sunday.



2. Set中next()的使用

[java] view plain copy
  1. Collection coll = new HashSet();  
  2. coll.add("Tody");  
  3. coll.add("is");  
  4. coll.add("Sunday.");  
  5.   
  6. // Output all elements by iterator  
  7. Iterator it = coll.iterator();  
  8. while(it.hasNext()) {  
  9.     System.out.print(it.next() + " ");  
  10. }  

输出:

is Sunday. Tody

 

由上面两个例子看出,在List和Set对象中,Iterator的next()方法返回的值是不一样的。

原因是List属于线性集合,元素是有序的,读取时是按照数组的形式,一个接一个的读取,存储也是按照add的顺序添加的。

而Set属于非线性的,是无序的,所以读取的元素与添加的顺序不一定一致。

对于HashSet,其实它返回的顺序是按Hashcode的顺序。

如果迭代也有序,则可以用LinkedHashSet。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值