Comparing two LinkedList<String> with ListIterator versus for loop and get(int index)

As it turns out AbstractList.equals() (which LinkedList uses) will do this automatically so use that. The code is:

public boolean equals(Object o) {
  if (o == this)
    return true;
  if (!(o instanceof List))
    return false;

  ListIterator<E> e1 = listIterator();
  ListIterator e2 = ((List) o).listIterator();
  while (e1.hasNext() && e2.hasNext()) {
    E o1 = e1.next();
    Object o2 = e2.next();
    if (!(o1 == null ? o2 == null : o1.equals(o2)))
      return false;
  }
  return !(e1.hasNext() || e2.hasNext());
}

So don't reinvent the wheel.

One final note: don't use get(index) to iterate over a LinkedList. It's O(n) access (O(1) for an ArrayList) so a LinkedList traversal using get(index) will be O(n2).


Random access into a LinkedList has horrible performance (it needs to start at one end and invoke next or similar repeatedly), so the ListIterator would be faster.