Iterator和Enumeration比较

Enumeration:
public interface Enumeration {
boolean hasMoreElements();
E nextElement();
}

Iterator:
public interface Iterator {
boolean hasNext();
E next();
void remove();
}
(1) 函数接口不同
Enumeration只有2个函数接口。通过Enumeration,我们只能读取,而不能对数据进行修改。
Iterator只有3个函数接口。Iterator除了能读取之外,也能数据进行删除操作。

(2) Iterator支持fail-fast机制,而Enumeration不支持。
Enumeration 是JDK 1.0添加的接口。使用到它的函数包括Vector、Hashtable等类,这些类都是JDK 1.0中加入的,Enumeration存在的目的就是为它们提供遍历接口。Enumeration本身并没有支持同步,而在Vector、Hashtable实现Enumeration时,添加了同步。
而Iterator 是JDK 1.2才添加的接口,它也是为了HashMap、ArrayList等集合提供遍历接口。Iterator是支持fail-fast机制的:当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。

fail-fast简介http://www.cnblogs.com/skywang12345/p/3308762.html
fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。
例如:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。
fail-fast机制,是一种错误检测机制。它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生。若在多线程环境下使用fail-fast机制的集合,建议使用“java.util.concurrent包下的类”去取代“java.util包下的类”。
private static List list = new ArrayList();
替换为
private static List list = new CopyOnWriteArrayList();

猜你喜欢

转载自blog.csdn.net/q1015189243/article/details/85337595