What is the time complexity of a size() call on a LinkedList in Java?

Martin Andersson picture Martin Andersson · May 14, 2009 · Viewed 26.5k times · Source

As the title asks, I wonder if the size() method in the LinkedList class takes amortized O(1) time or O(n) time.

Answer

GreenieMeanie picture GreenieMeanie · May 14, 2009

It's O(1). You can google for the source code and you will come to such:

From http://www.docjar.com/html/api/java/util/LinkedList.java.html

All of the Collection classes I have looked at store a the size as a variable and don't iterate through everything to get it.