java 枚举 迭代_Java 迭代与枚举

本文介绍了Java中遍历集合的两种方式——迭代和枚举,对比了它们的速度和内存消耗。枚举适用于简单遍历,而迭代器在多线程环境下更安全,能防止并发修改异常。在迭代过程中,只有迭代器的remove()方法能安全地删除元素,而枚举则不支持此操作。示例代码展示了这两种遍历方式的差异和用法。
摘要由CSDN通过智能技术生成

原标题:Java 迭代与枚举

ImportNew - MarkGZ

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

迭代与枚举的差异:

枚举比迭代快两倍而且消耗更少的内存。

枚举更适合基本需求,而迭代是相对更安全,

因为在遍历集合的时候,迭代器会阻止其他线程修改集合对象。

如果有其他线程要修改集合对象,会立即抛出ConcurrentModificationException。

我们称其为快速失败迭代器,因为它快速,明了的抛出了异常。

下面是代码示例;

Vector aVector = new Vector();

aVector.add("I");

aVector.add("am");

aVector.add("really");

aVector.add("good");

Enumeration anEnum = aVector.elements();

Iterator anItr = aVector.iterator();

// Traversal using Iterator

while(anItr.hasNext())

{

if ()

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

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

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()是唯一一种可以在迭代过程中安全修改集合的方式。

在枚举中,没有安全的方式可以在遍历集合的时候删除元素。返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值