本文介紹一下Iterator和Enumeration的區別及其效率java
Iterator是一個接口,它的源碼以下:dom
package java.util; import java.util.function.Consumer; public interface Iterator<E> { //返回迭代器剛越過的元素的引用,返回值是Object,須要強制轉換成本身須要的類型 boolean hasNext(); //判斷容器內是否還有可供訪問的元素,返回值是E E next(); //刪除迭代器剛越過的元素 default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
Enumeration也是一個接口,它的源碼以下:函數
package java.util; public interface Enumeration<E> { boolean hasMoreElements(); E nextElement(); }
從源碼能夠看出,Iterator除了能讀取集合的數據以外,也能數據進行刪除操做;而Enumeration只能讀取集合的數據,而不能對數據進行修改。ui
Iterator支持fail-fast機制,而Enumeration不支持fail-fast機制。Enumeration 是JDK 1.0添加的接口。使用到它的函數包括Vector、Hashtable等類,這些類都是JDK 1.0中加入的。Iterator是JDK1.2添加的接口,Iterator是基於Enumeration實現的,同時Iterator支持fail-fast機制,因此Iterator遍歷集合時會比Enumeration遍歷集合慢一些。spa
使用一個Hashtable集合,而後分別經過 Iterator 和 Enumeration 去遍歷它,比較它們的效率。代碼以下:code
package com.xyfer; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; public class Test { public static void main(String[] args) { int n; Random r = new Random(); Hashtable t = new Hashtable(); for (int i = 0; i < 10000; i++) { n = r.nextInt(1000); t.put(i, n); } iterateHashtable(t); enumeration(t); } //使用Iterator遍歷Hashtable private static void iterateHashtable(Hashtable t) { long start = System.currentTimeMillis(); Iterator i = t.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Entry) i.next(); //System.out.println("key:" + entry.getKey() + "value:" + entry.getValue()); } long end = System.currentTimeMillis(); useTime(start,end); } //使用Enumeration遍歷Hashtable private static void enumeration(Hashtable t) { long start = System.currentTimeMillis(); Enumeration enu = t.elements(); while (enu.hasMoreElements()) { enu.nextElement(); //Enumeration em = (Enumeration) enu.nextElement(); //System.out.println(enu.nextElement()); } long end = System.currentTimeMillis(); useTime(start,end); } //計算遍歷Hashtable所耗時間 private static void useTime(long start,long end) { System.out.println("耗時:"+(end-start)+"ms"); } }
控制檯打印結果:blog
從控制打印結果來看,Iterator遍歷集合時確實會比Enumeration遍歷集合慢一些。接口