Reputation: 86085
I am wondering if we can use index to access List
For example:
List<Integer> list;
list[5] //blah....
Upvotes: 35
Views: 101726
Reputation: 989
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).
Upvotes: 8
Reputation: 29680
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).
Upvotes: 3
Reputation: 36229
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.
Upvotes: 4
Reputation: 15656
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.
Upvotes: 70
Reputation: 52185
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.
Upvotes: 6