Can we use index like array index to access List?

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

I am wondering if we can use index to access List

For example:

List list; 

list[5]     //blah....
相关标签:
7条回答
  • 2020-12-03 07:30

    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.

    0 讨论(0)
  • 2020-12-03 07:35

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

    0 讨论(0)
  • 2020-12-03 07:35

    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.

    0 讨论(0)
  • 2020-12-03 07:42

    No, you can't do this in Java.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-03 07:45

    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.

    0 讨论(0)
提交回复
热议问题