Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing Element In linkedList

LinkedList 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 ask is, If LinkedList internally created nodes for each element then How Indexing concept have been comes into considering accessing the element (linkedList.get(1);)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading