简体   繁体   English

为什么运行时间复杂(清单 <Object> )list.size()是O(1)吗?

[英]Why the running time complexity of (List<Object>) list.size() is O(1)?

From here I understood that the complexity of some static arr is O(1) 这里我知道一些静态arr的复杂度为O(1)

But for dynamic array the size is never set, so how the complexity will be constant? 但是对于动态数组,永远不会设置大小,那么复杂度将如何保持不变? Even Oracle documentation says so. 甚至Oracle 文档也是如此。

static int count =  0;
public static void main(String[] args) {
    List.of(1, 2, 3, 4, 5).forEach(x -> count++); // Java-10
    System.out.println(count);
}

this code should determine the size of the list, if this runs for O(n) times then why 此代码应确定列表的大小,如果运行了O(n)次,那么为什么

List.of(1, 2, 3, 4, 5).size();

is O(1) 是O(1)

As per, for example, here , ArrayList will store the current size as to make it immediately available. 例如, 在这里 ,ArrayList将存储当前大小以使其立即可用。 Other lists would be similar, as it's a common optimization. 其他列表将是相似的,因为这是常见的优化。 (Eg. LinkedList ) (例如LinkedList

While forming the List the time complexity is not O(1) . 在形成列表时,时间复杂度不是O(1) After list is formed the size is saved internally in the list. 列表形成后,尺寸将内部保存在列表中。 After that when we call List.size() it just return the saved size with time complexity O(1) 之后,当我们调用List.size()它只返回保存的大小,时间复杂度为O(1)

You're specifically asking why List.of(1, 2, 3, 4, 5).size() is O(1) . 您是在问为什么List.of(1, 2, 3, 4, 5).size()O(1)

While other answers have correctly said that implementations such as ArrayList and LinkedList explicitly store the lists size as a field of the list, that doesn't actually answer your question, because List.of​(E... elements) doesn't use those implementations. 虽然其他答案正确地指出诸如ArrayListLinkedList实现将列表大小显式存储为列表的字段,但实际上并不能回答您的问题,因为List.of​(E... elements)不使用这些实现。

List.of(E... elements) is varargs, which means that internally it is actually List.of(E[] elements) and the compiler builds a fixed array for you. List.of(E... elements)List.of(E... elements) ,这意味着在内部它实际上是List.of(E[] elements) ,并且编译器为您构建了一个固定数组。 In your case, that array is exactly 5 in size. 在您的情况下,该数组的大小恰好为5。

Although the implementation is really different, building an immutable list, the E[] is turned into a list similarly to how Arrays.asList​(T... a) does it, ie by wrapping the array in a List implementation that uses the array directly. 虽然实现真正的不同,建设一个不可变列表中, E[]变成一个列表类似于如何Arrays.asList​(T... a)这样做,即通过包装阵列中的List实现,它使用的直接数组。

As such, the list size of very well known, because the size is the length of the backing array . 这样,列表的大小是众所周知的,因为列表的大小就是支持数组的长度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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