Java - What is difference between Enumeration and Iterator?

http://javarevisited.blogspot.sg/2010/10/what-is-difference-between-enumeration.html

Because sometimes I can't open this page without proper proxy configuration, so I have to copy some content here.


Both Iterator and Enumeration provides way to traverse or navigate through entire collection in Java.
Enumeration is a legacy class and not all Collection supports it e.g. Vector supports Enumeration but ArrayList doesn't.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration

hasMoreElement()
nextElement()
N/A

Iterator

hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值