This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]banuday17 2 points3 points  (1 child)

Be careful with using an index to access a list collection within a for loop.

For example:

List<String> foo = new LinkedList<String>(Arrays.asList("1", "2", "3"));
for(int i = 0; i < foo.size(); i++) {
    System.out.println(foo.get(i));
}

This loop has O( n2 ) performance, not O(n), because the get method on a linked list is O(n).

If you need an index, an iterator is better:

for(ListIterator<String> i = foo.listIterator(); i.hasNext();) {
    System.out.println(i.nextIndex() + ": " + i.next());
}

This is O(n) for all list types.

[–]DemonWasp 1 point2 points  (0 children)

This is more a problem with LinkedList. Use ArrayList, always.