`Java` `List` 方法 `size` 是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2205498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:43:01  来源:igfitidea点击:

How does `Java` `List` method `size` work?

javalist

提问by coder

In Java, there is a Listinterface and size()method to compute the size of the List.

在 Java 中,有一个List接口和size()方法来计算List.

  • When I call List.size(), how does it count?
  • Is it counted linearly, or the count is determined and just the value is returned back when size()?
  • 当我打电话时List.size(),它是如何计算的?
  • 它是线性计数的,还是确定了计数并且仅在何时返回值size()

采纳答案by Yann Ramin

Size is defined as the number of elements in the list. The implementation does not specify how the size() member function operates (iterate over members, return stored count, etc), as List is an interface and not an implementation.

大小定义为列表中元素的数量。该实现没有指定 size() 成员函数如何操作(迭代成员、返回存储的计数等),因为 List 是一个接口而不是一个实现。

In general, most concrete List implementations will store their current count locally, making size O(1) and not O(n)

通常,大多数具体的 List 实现将在本地存储它们的当前计数,使大小为 O(1) 而不是 O(n)

回答by Asaph

java.util.Listis an interface, not a class. The implementation of the size()method may be different for different concrete implementations. A reasonable implementation for a size()method on a java.util.Listimplementation would be to initialize an instance member of type intto zero and increment/decrement it appropriately as items are added to/removed from the List. The size()method could simply return the aforementioned instance member. This is of course, simply an example. For complete detail, you could always look at the sources for the built-in Listimplementations. All the source code has been available for years.

java.util.List是一个接口,而不是一个类。size()对于不同的具体实现,该方法的实现可能会有所不同。实现上的size()方法的合理实现是java.util.List将类型的实例成员初始化int为零,并随着项目添加到List. 该size()方法可以简单地返回上述实例成员。这当然只是一个例子。有关完整的详细信息,您可以随时查看内置List实现的来源。所有源代码已经可用多年。