1.What is an Iterator ?
4.What is the difference between Enumeration and Iterator?
5.How is ListIterator?
- The Iterator interface is used to step through the elements of a Collection.
- Iterators let you process each element of a Collection.
- Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
- Iterator is an Interface implemented a different way for every Collection.
To use an iterator to traverse through the contents of a collection, follow these steps:
- Obtain an iterator to the start of the collection by calling the collection iterator() method.
- Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
- Within the loop, obtain each element by calling next().
Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.
4.What is the difference between Enumeration and Iterator?
Enumeration | Iterator |
---|---|
Enumeration doesn't have a remove() method | Iterator has a remove() method |
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects | Can be abstract, final, native, static, or synchronized |
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.
ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element
EmoticonEmoticon