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.
As it turns out
AbstractList.equals()(whichLinkedListuses) will do this automatically so use that. The code is:So don’t reinvent the wheel.
One final note: don’t use
get(index)to iterate over aLinkedList. It’s O(n) access (O(1) for anArrayList) so aLinkedListtraversal usingget(index)will be O(n2).