Friday, 24 May 2013

JAVA INTERVIEW QUESTIONS - Iterator

1.What is an Iterator ?

  • 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.

2.How do you traverse through a collection using its Iterator?
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().
3.How do you remove elements during Iteration?
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?
EnumerationIterator
Enumeration doesn't have a remove() methodIterator has a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objectsCan be abstract, final, native, static, or synchronized
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.

5.How is ListIterator?
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