I am wondering if we can use index to access List
For example:
List<Integer> list;
list[5] //blah....
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.
list[5] is not possible in Java, although he didn't mention any alternatives.list.get(int) or, if really needed, list.toArray()[5] [:-)toArray just to access an element.