Search code examples
javacollections

Accessing Element In linkedList


LinkedList<String> linkedList = new LinkedList<>();

linkedList.add("Java");
linkedList.add("Python");
linkedList.get(1); 

Internal code flows for get

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

private void checkElementIndex(int index) {
     if (!isElementIndex(index))
     throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

I am calling, linkedList.get(1); to get the second element in an linked list. My question is, uf LinkedList internally created nodes for each element, then how does an indexing concept come into consideration for accessing the element (linkedList.get(1))?


Solution

  • This index is not like the array index in ArrayList . In a LinkedList, the get by index method under the hood is just a for loop, and since the list is ordered, it will simply return the element you need by looping through elements of the list.

    Look inside LinkedList for the Node<E> node(int index) method, which is called in the get(int index) method.