What is complexity of size() for TreeSet portion view in Java

后端 未结 1 1626
闹比i
闹比i 2020-12-20 15:37

I\'m wondering what is the time complexity of size() for portion view of TreeSet.

Let say I\'m adding random numbers to set (and I do not care about dup

相关标签:
1条回答
  • 2020-12-20 16:06

    Looks like complexity of size () is O(N), because it may call TreeMap.NavigableSubMap.EntrySetView.size () which is implemented like this (Oracle JDK 1.7.0_13):

    public int size() {
        if (fromStart && toEnd)
            return m.size();
        if (size == -1 || sizeModCount != m.modCount) {
            sizeModCount = m.modCount;
            size = 0;
            Iterator i = iterator();
            while (i.hasNext()) {
                size++;
                i.next();
            }
        }
        return size;
    }
    
    0 讨论(0)
提交回复
热议问题