简体   繁体   中英

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

Do TreeMap and TreeSet keep track of how many items they contain, or do they have to count them every time you call size() ? The javadocs remain mute on the subject.

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

For future reference, the google search was "java source code treemap". (I'm not saying that to be snarky -- it's not entirely obvious that the source code would be out there for the googlin').

tl;dr version is that they keep track, so it's O(1).

是的,它们会跟踪它们包含多少个对象,因此调用size()会产生O(1)运行时。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM