Câu hỏi phỏng vấn Java
Câu hỏi

What’s the difference between Enumeration and Iterator interfaces?

Câu trả lời

The difference between the Enumeration and Iterator interfaces in Java primarily revolves around their design, functionality, and applicability within the Java Collections Framework.

Enumeration Interface

  1. Legacy Interface: Enumeration is one of the earliest interfaces introduced in Java (JDK 1.0). It is considered a legacy interface and is primarily used with legacy classes such as Vector and Hashtable[1][2][4].
  2. Functionality: Enumeration allows only the basic functionality of traversing through a collection of elements. It provides two methods: hasMoreElements() and nextElement(), which are used to check if there are more elements and to get the next element, respectively[1][2][4].
  3. Read-only Access: It does not support element removal or any modification to the collection while iterating, making it a read-only interface[1][2][3][4].
  4. Fail-safe: Enumeration is fail-safe, meaning it does not throw a ConcurrentModificationException if the collection is modified while iterating through it. This is because it is designed to be used with legacy classes that are generally synchronized[6].

Iterator Interface

  1. Introduced in JDK 1.2: Iterator was introduced later as part of the Java Collections Framework overhaul in JDK 1.2. It is not a legacy interface and is meant to replace Enumeration[1][2][4].
  2. Enhanced Functionality: Iterator extends the capabilities of Enumeration by providing three methods: hasNext(), next(), and remove(). These methods check if there are more elements, return the next element, and remove the last element returned by the iterator from the collection, respectively[1][2][4].
  3. Modification Support: Unlike Enumeration, Iterator allows modifying the collection during iteration by providing the remove() method. This method can be used to safely remove elements from the collection without risking ConcurrentModificationException[1][2][4].
  4. **Fa...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is the difference between Serial and Throughput Garbage collector?

senior

When to use LinkedList over ArrayList in Java?

junior

How are the JSP requests handled?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào