简体   繁体   English

由于 ArrayList 实现了 RandomAccess 接口,它在遍历时是否比 Array 更快

[英]As ArrayList implements RandomAccess interface, is it faster than Array while traversing

As ArrayList implements RandomAcess interface, it finds element at any index with same amount of time.由于 ArrayList 实现了 RandomAcess 接口,因此它可以在相同的时间内找到任何索引处的元素。 Does it use same interface while traversing.遍历时是否使用相同的接口。 And if it does then is it faster than Array traversing?如果确实如此,它是否比数组遍历更快?

Does it use same interface while traversing遍历时是否使用相同的接口

What interface are you talking about?你说的是什么接口? List<T> ? List<T> ? well yes.嗯,是。 LinkedList<T> also implements List<T> , but not RandomAccess . LinkedList<T>也实现了List<T> ,但没有实现RandomAccess

And if it does then is it faster than Array traversing如果确实如此,它会比数组遍历更快

An ArrayList is using an array under the hood, so it cannot be faster than an array. ArrayListArrayList使用数组,因此它不能比数组快。

An ArrayList behaves just like an array. ArrayList行为就像一个数组。

It is essentially a wrapper class for an array that permits it to:它本质上是一个数组的wrapper class ,允许它:

  1. Grow dynamically动态增长
  2. Allow for the selection and deletion of elements.允许选择和删除元素。
  3. Access its elements just like an array.就像访问数组一样访问它的元素。
  4. And some other additional features such as searching for elements.以及其他一些附加功能,例如搜索元素。

Except for item 3 above all are implemented as efficiently as possible but still add to the cost as they would if you had to provide that capability when using outright arrays.除了上面的第 3 项之外,所有这些都尽可能高效地实现,但仍然会增加成本,如果您在使用直接数组时必须提供该功能,则会增加成本。

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

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