Link to home
Start Free TrialLog in
Avatar of Jay Roy
Jay RoyFlag for United States of America

asked on

ListIterator v/s Iterator

hi experts
Can anyone explain Iterator v/s Listiterator with a very simple ArrayList example.
thanks.
Avatar of kaufmed
kaufmed
Flag of United States of America image

What programming language is this for?
Avatar of Jay Roy

ASKER

Java
I sent a note to the admins to add this to the Java zone.
Have you looked at the Javadocs for ListIterator? I don't know whether I could really say more without just repeating what is already documented.

Have a read of that link and then if you still have more specific questions, post back here!
Avatar of Jay Roy

ASKER

Well I read the docs,  I am looking for a simple example of iterating an arraylist with list iterator. I have used  iterator in the past. Just want to understand a practical usage of list iterator.
I think  mccarl  above answered your question.  However, you can always check the java2s site for examples of java code, like this:

   ArrayList<String> al = new ArrayList<String>();
// add some data to al here then iterate
    Iterator<String> itr = al.iterator();
    while (itr.hasNext()) {
      String element = itr.next();
      System.out.print(element + " ");
    }
Avatar of Jay Roy

ASKER

The focus is on ListIterator here not Iterator.
When would I use a ListIterator instead of
iterator?
Ah -- it's beginning to sound like homework.  

But you can look at various code examples, if that helps:
http://www.java2s.com/Code/JavaAPI/java.util/ArrayListiterator.htm

You should check the Java API as mccarl suggested and try them or ask a specific question.  I don't think there's much difference between the two, except that of course ListIterator is meant to work on List collections and an Iterator can work on other types of collections.
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jay Roy

ASKER

thanks for the example. I also see they use ListIterator heavily in Java api, for instance
Collections.sort(list);

    public static <T extends Comparable<? super T>> void sort(List<T> list) {
        Object[] a = list.toArray();
        Arrays.sort(a);
        ListIterator<T> i = list.listIterator();
        for (int j=0; j<a.length; j++) {
            i.next();
            i.set((T)a[j]);
        }
    }

Open in new window

Yeah, so the "set()" method is the other main addition that ListIterator has over Iterator. Thinking a bit more about it, that is probably the method that may have the most real world use.
Avatar of Jay Roy

ASKER

true, there is also add(e) which is intresting.