开发者

Can we use index like array index to access List<T>?

I am wondering if we can use index to access List

For example:

List<Int开发者_开发技巧eger> list; 

list[5]     //blah....


Since [] is an operator and java does not support operator overloading you can't use it with List. Instead you have to use the set(int index, T value) and get(int index) methods, which may be verbose but provide exact the same functionality.


List.get(int) allows you to access elements using the index.


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).


You can access List elements using their index through the use of the get method:

get

public Object get(int index)

Returns the element at the specified position in this list.

Parameters: index - index of element to return.

Returns: the element at the specified position in this list.

Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()).

Keep in mind that the index in Lists is 0 based.


No, you're restricted to List.get (i).

The brackets [] are defined on syntax level, not as method-name, so you can't override them. They are used just for arrays exclusively.

If you like to migrate to Scala, a more modern language for the JVM, you'll find an unified access to arrays and lists, but both with () parentheses.


an alternative to using get(int) is to create an Array using toArray()

List<T> list = ...

Object[] array = list.toArray();

if T is known, toArray(T[]) can be used to return T[] instead of Object[].
The use of toArray is only meaningful, instead of get, if an array is really needed (lots of accesses).


No, you can't do this in Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜