Java compilations: TreeMap.size () and TreeSet.size (): O (1) or O (n)?

Do TreeMap

and TreeSet

keep track of the number of items they contain, or should they count them every time you call size()

? The Javadoks remain mute on this issue.

+3


source to share


2 answers


Take a look:

http://www.docjar.com/html/api/java/util/TreeMap.java.html

http://www.docjar.com/html/api/java/util/TreeSet.java.html



Later, the Java source treemap was used to search Google. (I'm not saying it was snarky - it's not entirely obvious that the source code will be there for googlin ').

tl; dr version is what they track, so O (1).

+8


source


Yes, they keep track of how many objects they contain, so the call size()

either gives O (1) runtime.



+1


source







All Articles