Iterator and ListIterator are interfaces in Java that allow us to iterate over a collection of objects. However, there are some differences between them:

  1. The Iterator interface can be used to iterate over any collection, whereas the ListIterator interface can be used to iterate only over lists.
  2. The ListIterator interface extends the Iterator interface and provides additional methods to traverse the list in both forward and backward directions.
  3. With a ListIterator, you can add and remove elements from the list while iterating, but with an Iterator, you can only remove elements.

Here’s an example code that demonstrates the difference between the two:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IteratorVsListIteratorExample {

    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();
        myList.add("apple");
        myList.add("banana");
        myList.add("cherry");
        
        // Using Iterator to iterate over the list
        Iterator<String> it = myList.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        
        // Using ListIterator to iterate over the list in backward direction
        ListIterator<String> lit = myList.listIterator(myList.size());
        while (lit.hasPrevious()) {
            System.out.println(lit.previous());
        }
    }
}

In the above code, we have used an Iterator to iterate over the list in forward direction, and a ListIterator to iterate over the list in backward direction. Note that the ListIterator is created by passing the size of the list as the starting index, which allows us to iterate over the list in reverse order.