javalistiteratorlistiterator

for (ListIterator<E> it = listIterator(); it.hasNext(); ) VS for (ListIterator<E> it = list.listIterator(); it.hasNext(); )


Could someone tell me, if the for (ListIterator<E> it = listIterator(); it.hasNext(); ) part of the code should be instead written as for (ListIterator<E> it = list.listIterator(); it.hasNext(); ) where list is an reference to an instance of ArrayList or LinkedList class? Is both form acceptable and correct? Where should I use one over the other?

public int indexOf(E e) {
    for (ListIterator<E> it = listIterator(); it.hasNext(); )
        if (e == null ? it.next() == null : e.equals(it.next()))
            return it.previousIndex();
    // Element not found
    return -1;
}

Solution

  • for (ListIterator<E> it = listIterator(); it.hasNext(); )
    

    This code calls listIterator() of myself (this) and use its return value. The class where this code is written has higher chance to List is implement ed.

    for (ListIterator<E> it = list.listIterator(); it.hasNext(); )
    

    This code calls listIterator() of the instance reference to which is stored in list and use its return value. This code may appear everywhere to write routines.

    Both are acceptable, but whether thay are correct should depend on what you want to do.