Difference Between Java Enumeration and Iterator – Java枚举和迭代器的区别

最后修改: 2022年 10月 13日

1. Overview


In this tutorial, we’ll learn about Enumeration and Iterator in Java. We’ll also learn how to use them in code and what are the differences between them.


2. Introduction to Enumeration and Iterator


In this section, we’ll learn about Enumeration and Iterator conceptually and their use.


2.1. Enumeration


Enumeration has been present in Java since version 1.0. It’s an interface and any implementation allows one to access elements one by one. In simple terms, it’s used to iterate over a collection of objects such as Vector and Hashtable.


Let’s look at an example for Enumeration:


Vector<Person> people = new Vector<>(getPersons());
Enumeration<Person> enumeration = people.elements();
while (enumeration.hasMoreElements()) {
    System.out.println("First Name = " + enumeration.nextElement().getFirstName());

Here, we’re printing firstName of a Person using Enumeration. The elements() method provides a reference to Enumeration and by using that we can access elements one by one.

在这里,我们正在使用Enumeration打印PersonfirstNameelements() 方法提供了对Enumeration的引用,通过使用它,我们可以一个一个地访问元素。

2.2. Iterator

2.2. 迭代器

Iterator has been present in Java since 1.2 and is used to iterate over collections that were also introduced in the same version.


Next, let’s print firstName of a Person using Iterator. iterator() provides a reference to Iterator and by using that we can access elements one by one:

接下来,让我们使用Iterator来打印PersonfirstNameiterator() 提供了一个对Iterator的引用,通过使用它,我们可以一个一个地访问元素。

List<Person> persons = getPersons();
Iterator<Person> iterator = persons.iterator();
while (iterator.hasNext()) {
    System.out.println("First Name = " + iterator.next().getFirstName());

So, we can see Enumeration and Iterator are both present in Java since 1.0 and 1.2 respectively, and are used to iterate over a collection of objects one at a time.


3. Difference Between Enumeration and Iterator


In this table, we’ll understand the differences between Enumeration and Iterator:


Enumeration Iterator
Present since Java 1.0 to enumerate Vectors and Hashtables Present since Java 1.2  to iterate over Collections such as List, Set, Map, etc
Contains two methods: hasMoreElements() and nextElement() Contains three methods: hasNext(), next() and remove()
Methods have long names Methods have short and concise names
Have no methods to remove elements while iterating Have remove() to remove elements while iterating
asIterator() added in Java 9 gives Iterator on the top of Enumeration. However, remove() in this particular case throws UnsupportedOperationException forEachRemaining() added in Java 8 performs actions on the remaining elements

4. Conclusion


In this article, we’ve understood Enumeration and Iterator, how to use them using code examples, and the various differences between them.


All the code example used in this article is available over on GitHub.