Can we use index like array index to access List?

后端 未结 7 778
失恋的感觉
失恋的感觉 2020-12-03 06:45

I am wondering if we can use index to access List

For example:

List list; 

list[5]     //blah....
7条回答
  •  -上瘾入骨i
    2020-12-03 07:44

    There are plenty of good answers here, but I just want to point out that list.get(i) is the same as list[i] only if list is implemented with an array (i.e ArrayList). If it is a LinkedList you are not really indexing with get, but rather iterating.

    So if you use get() with the interface type List, especially in a loop, you should check how it's implemented, as get() with ArrayList is O(1) whereas get() with LinkedList is O(n) (much slower).

提交回复
热议问题