Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have two LinkedList objects that are always of the same size. I want to compare them to see if they are identical in content. What are the general performance and style implications of creating a ListIterator for each list and using a while hasNext loop versus using a counter (int i) and iterating from 0 to linkedlist.size() using linkedlist.get(i) to get and compare the values? Is there a better way that I'm overlooking?

The only thing I can think of is that the ListIterator method may be better in that I could more easily swap in another Comparable list later (not that I plan on it). I don't know what the two look like under the hood, so I'm not sure how I would compare them performance-wise.

like image 684
msilver Avatar asked Feb 24 '10 03:02

msilver


People also ask

Can we use ListIterator in LinkedList?

LinkedList listIterator() Method in Java LinkedList. listIterator() method is used to return a list-iterator containing the same elements as that of the LinkedList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method.

Why manipulation is fast in LinkedList?

Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. 3) An ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.

What is faster ArrayList or LinkedList?

ArrayList is faster in storing and accessing data. LinkedList is faster in manipulation of data.

Why retrieval is faster in ArrayList?

Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.


1 Answers

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).

like image 55
cletus Avatar answered Sep 27 '22 20:09

cletus