java Iterator 和 ListIterator 的不同使用方法

我们在使用List,Set的时候,为了实现对其数据的遍历,我们经常使用到了Iterator(跌代器)。使用跌代器,你不需要干涉其遍历的过程,只需要每次取出一个你想要的数据进行处理就可以了。 

但是在使用的时候也是有不同的。List和Set都有iterator()来取得其迭代器。对List来说,你也可以通过listIterator()取得其迭代器,两种迭代器在有些时候是不能通用的,Iterator和ListIterator主要区别在以下方面: 

1. ListIterator有add()方法,可以向List中添加对象,而Iterator不能。 

2. ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。 

3. ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。 

4. 都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iierator仅能遍历,不能修改。 

因为ListIterator的这些功能,可以实现对LinkedList等List数据结构的操作。其实,数组对象也可以用迭代器来实现。 

org.apache.commons.collections.iterators.ArrayIterator就可以实现此功能。一般情况下,我们使用Iterator就可以了,如果你需要进行记录的前后反复检索的话,你就可以使用ListIterator来扩展你的功能,(有点象JDBC中的滚动结果集)。 

ListIterator 的方法: 
Method Summary
 void	add(Object o) 
          Inserts the specified element into the list (optional operation).
 boolean	hasNext() 
          Returns true if this list iterator has more elements when traversing the list in the forward direction.
 boolean	hasPrevious() 
          Returns true if this list iterator has more elements when traversing the list in the reverse direction.
 Object	next() 
          Returns the next element in the list.
 int	nextIndex() 
          Returns the index of the element that would be returned by a subsequent call to next.
 Object	previous() 
          Returns the previous element in the list.
 int	previousIndex() 
          Returns the index of the element that would be returned by a subsequent call to previous.
 void	remove() 
          Removes from the list the last element that was returned by next or previous (optional operation).
 void	set(Object o) 
          Replaces the last element returned by next or previous with the specified element (optional operation).


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值