Enumeration 和Iterator的异同
时间: 2024-04-22 07:25:00 浏览: 19
Enumeration 和 Iterator 都是 Java 中用于遍历集合(如列表、集合等)中元素的接口,它们有一些相似之处,但也有一些重要的区别。
相同点:
1. 都是用于遍历集合中的元素。
2. 都提供了 `hasNext()` 方法用于判断是否还有下一个元素。
3. 都提供了 `next()` 方法用于获取下一个元素。
4. 都不支持对集合进行修改操作。
不同点:
1. 来源:Enumeration 是在 Java 1.0 中引入的,而 Iterator 是在 Java 1.2 中引入的,Iterator 是 Enumeration 的增强版。
2. 接口方法:Enumeration 接口只有两个方法 `hasMoreElements()` 和 `nextElement()`,而 Iterator 接口除了 `hasNext()` 和 `next()` 方法外,还增加了 `remove()` 方法,用于从集合中移除当前元素。
3. 遍历方式:Enumeration 只支持单向遍历,只能从前往后遍历元素,而 Iterator 支持双向遍历,可以在遍历过程中使用 `hasPrevious()` 和 `previous()` 方法进行反向遍历。
4. 兼容性:Enumeration 在 Java 2 平台已经被废弃,不推荐使用,而 Iterator 是目前常用的遍历集合的方式。
总结来说,Enumeration 是 Iterator 的早期版本,功能较为简单,只能单向遍历,而 Iterator 在此基础上增加了对集合的修改操作,并且支持双向遍历。因此,在新的代码中,建议使用 Iterator 进行集合的遍历操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)