枚举和迭代器
在Java中有许多数据结构充当集合,比如向量、哈希表和实现Java集合框架的类(即HashMap、HashSet、ArrayList、TreeSet、TreeMap、LinkedList、LinkedHashMap和LinkedHashSet)。在Java中,有许多方法可以遍历对象的各个元素。Java提供了两个接口来简化这项任务。枚举和迭代器是java中的两个接口。util包that provide functionality to enumerate through sequences or objects with a set of items. Enumerator was introduced in JDK 1.0 and Iterator which was introduced in JDK 1.2 virtually duplicates the functionality of the Enumerator (within the Collections Framework).
枚举是什么?
枚举是Java中的一个公共接口,是在JDK 1.0中引入的,它提供了枚举元素序列的能力。它在java下找到。util包。当Enumeration接口由一个对象实现时,该对象可以生成一系列元素。枚举接口有两个方法。hasMoreElements()方法将测试此枚举是否包含更多元素,而nextElement()将返回序列中的下一个元素(如果至少还有一个元素)。换句话说,通过连续调用nextElement(),程序员可以访问序列中的单个元素。例如,要使用Enumerator打印Vector v1中的所有元素,可以使用以下代码片段。
枚举e = v1.elements();
而(e.hasMoreLements ()) {
System.out.println (e.nextElement ());
}
枚举器还可以用于定义SequenceInputStream对象的输入流。
迭代器是什么?
Iterator是Java中的公共接口。util包,which allows iterating through elements of the collections objects that implement the Collections framework (such as ArrayList, LinkedList, etc.). This was introduced in JDK 1.2 and replaced the Enumerator within the Java Collections Framework. Iterator has three methods. The method hasNext() tests whether there are remaining elements in the collection and the next() method returns the next element in the series. The remove() method can be used to remove the current element from the underlying collection. For example, to print all elements in Vector v1 using Iterator, the following code snippet can be used.
迭代器i = v1.elements();
而(i.hasNext ()) {
System.out.println (e.next ());
}
枚举和迭代器的区别是什么?
尽管,枚举和迭代器是java中的两个接口。util包,which allow iterating/enumerating through elements of a series, they have their differences. Actually, Iterator, which was introduced after Enumeration, replaces the Enumeration within the Java Collections framework. Unlike Enumeration, Iterator is fail-safe. This means that concurrent modifications (to the underlying collection) are not allowed when Iterator is used. This is very useful in multi-threaded environments where there is always a risk of concurrent modifications. In the event of a concurrent modification, the Iterator object will throw a ConcurrentModificationException. Iterator has shorter method names compared to Enumerator. Furthermore, iterator has the additional functionality of deleting elements during the iteration (which is not possible using Enumerator). So, if there is a need to remove elements from the collection, Iterator is the only option that can be considered.
留下一个回复