Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do array(or ArrayList) and LinkedList perform the same when iterating? [duplicate]

I know arrays are faster at getting and setting, while LinkedLists are better at adding and removing elements, but what about when iterating? A more "traditional" for(i=0;i<intList.size();i++) would definitely make LinkedLists slower since you'd have to get the element at index i every time. But what if I use for(int i : intList)? How does it work under the hood for this instance? For example:

LinkedList<Integer> intList = new LinkedList();
/*
populate list...
*/
for (int i : intList) {
    //do stuff
}

I imagine that there's no need to get an specific element when going through the whole List, so it should be possible to have some sort of loop implementation where performance is about the same. Though I don't know how exactly how for is implemented for this example so I can't be sure if this is it.

like image 766
Janilson Avatar asked Nov 07 '22 08:11

Janilson


1 Answers

They both iterate at the same speed, O(1) when using foreach. For further information, read this post.

like image 109
Raymo111 Avatar answered Nov 14 '22 21:11

Raymo111