欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

迭代与枚举,枚举

来源: javaer 分享于  点击 11350 次 点评:46

迭代与枚举,枚举


正如大家所知,迭代和枚举主要用于遍历集合对象。枚举可以应用于Vector和Hashtable,迭代主要用于集合对象。

迭代与枚举的差异:
* 枚举比迭代快两倍而且消耗更少的内存。
* 枚举更适合基本需求,而迭代是相对更安全,
* 因为在遍历集合的时候,迭代器会阻止其他线程修改集合对象。
* 如果有其他线程要修改集合对象,会立即抛出ConcurrentModificationException。
* 我们称其为快速失败迭代器,因为它快速,明了的抛出了异常。

下面是代码示例;

Vector <String> aVector = new Vector<String>(); 
aVector.add("I"); 
aVector.add("am"); 
aVector.add("really"); 
aVector.add("good");
Enumeration <String> anEnum = aVector.elements(); 
Iterator <String> anItr  = aVector.iterator();
// Traversal using Iterator 
while(anItr.hasNext()) 
{ 
   if (<someCondition>) 
      // This statement will throw ConcurrentModificationException. 
      // Means, Iterator won't allow object modification while it is 
      // getting traversed. Even in the same thread. 
      aVector.remove(index); 
   
   System.out.println(anItr.next()); 
}
// Traversal using Enumeration 
while(anEnum.hasMoreElements()) 
{ 
   if (<someCondition>) 
      aVector.remove(index); 
   
   System.out.println(anEnum.nextElement()); 
}

但是迭代器提供了一种安全的方式,可以迭代过程中删除从底层集合中的元素。
看下迭代器的实现。Collection的其他实现类支撑了这里的remove()方法。

public interface Iterator 
{ 
   boolean hasNext(); 
   Object next(); 
   void remove(); // Optional 
}

上面的程序可以重写为:

while(anItr.hasNext()) 
{ 
   System.out.println(anItr.next());

   if (<someCondition>) 
      anItr.remove();
   // Note: 
   // Before using anItr.remove(), the Iterator should 
   // point to any of its elements. The remove() removes the 
   // element which the Iterator corrently pointing to.
   // Otherwise it will throw IllegalStateException  

}

需要注意的是:Iterator.remove()是唯一一种可以在迭代过程中安全修改集合的方式。
在枚举中,没有安全的方式可以在遍历集合的时候删除元素。

原文链接: javabeanz 翻译: Wld5.com - MarkGZ
译文链接: http://www.wld5.com/10492.html
[ 转载请保留原文出处、译者和译文链接。]

相关栏目:

用户点评