Difference between Iterator and ListIterator

difference between iterator and list iterator featured image

Difference between Iterator and ListIterator:

Understanding the difference between iterator and listiterator will help us to use the correct one at correct place for correct requirements. Also this is one of the famous java interview question for experienced developers. If you would like to read just the differences you can continue going through this post.

But if you like to explore complete information’s like methods, sample programs, when to use, features & limitations of iterator and listiterator then I would recommend you to go through the below links.

 

Iterator in Java with Examples

ListIterator in Java with Examples

 

ListIterator:

  • Can be used to iterate List/Set/Map collection objects. [eg: ArrayList/HashSet/HashMap]
  • Traverse can be in both forward(hasNext()/next()) and reverse/backward(previous() and hasPrevious()) directions.
  • We can add() new elements/set list elements using listiterator.
  • Easy to find the next and previous element indexes.
  • Methods available:
    • add()
    • set()
    • remove()
    • previousIndex()
    • nextIndex()
    • next()
    • hasNext()
    • previous()
    • hasPrevious()

 

Iterator:

  • Can be used to iterate only List collection object. [eg: ArrayList/LinkedList]
  • Traverse can be only in forward(hasNext()/next()) direction.
  • We can’t either add/set collection objects using iterator.
  • We can’t find next/previous element indexes.
  • Methods available:
    • hasNext()
    • next()
    • remove()

 

Similarities between Iterator and Listiterator:

  • Both are interfaces. ListIterator interface extends Iterator interface.
  • Both are in java.util packages.
  • Both can iterate in forward direction
  • Both has remove() method.

 

634 total views, 1 views today

About: Mirthbees

Blogger, Innovator, Developer and Enterpreneur. Founder of GuruRecharge, Readymade online recharge script. Lead Developer in Bookrate.in