What is the difference between Enumeration and Iterator ?

Java Core Tech 专栏收录该内容
74 篇文章 0 订阅
What are differences between Enumeration and Iterator This question is from early ages of interview , I have not seen this question on recent interviews but it was common during 2006-2007 , now days questions like implementation of HashMap, ConcurrentHashMap etc has take its place, nonetheless its very useful to know fundamental difference between Iterator and Enumeration.Some time its also asked as Iterator vs Enumeration or Enumeration vs Iterator which is same. important point to note is that both Iterator and Enumeration provides way to traverse or navigate through entire collection in java

Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0 while iterator was introduced later. Iterator can be used with Java arraylist, java hashmap keyset and with any other collection classes.


difference between iterator and enumeration in javaAnother similarity between Iterator and Enumeration in Java is that functionality of Enumeration interface is duplicated by the Iterator interface.

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. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

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()



Read more: http://javarevisited.blogspot.com/2010/10/what-is-difference-between-enumeration.html#ixzz2ki1uv7nU
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

chenyujin999

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值