加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

用Iterator实现遍历集合

发布时间:2021-07-06 05:26:38 所属栏目:大数据 来源: https://www.cnblogs.com/xiado
导读:使用Collection类的Iterator,可以方便的遍历Vector,ArrayList,LinkedList等集合元素,避免通过get()方法遍历时,针对每一种对象单独进行编码。 示例: [java] view plaincopy Collection?coll?=? new?Vector();? //LinkedList();?//ArrayList();?? coll.add

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

示例:

[java] view plaincopy
  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.

?

1.hasNext()函数的API解释

boolean java.util.Iterator.hasNext()

?

hasNext

boolean hasNext()
@H_301_72@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: @H_301_72@ true if the iteration has more elements

---------------------------------------------------------

2.next()函数的API解释

Object java.util.Iterator.next()

?

next

E next()
@H_301_72@Returns the next element in the iteration.

?

@H_301_72@ Returns: @H_301_72@the next element in the iteration Throws: @H_301_72@ NoSuchElementException - if the iteration has no more elements

?

[java] view plaincopy
  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。

http://topic.csdn.net/u/20101227/09/63a23d05-7f15-4b0e-9287-e97f96ba4349.html?77188351

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读