What is the LinkedList.get(int index) method in Java?
A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value and the reference part has the address link to the next element.
The elements are not indexed, so random access like an array is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListclass is theimplementation of the doubly-linked list A kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. ListandDequeinterfaces. TheLinkedListclass is present in thejava.utilpackage.
The get method
The get method can be used to get the element at the specified index of the LinkedList.
Syntax
public E get(int index);
Parameters
This method takes the index of the element to be retrieved as an argument.
Return value
This method returns the element at the specified index of the list.
The IndexOutOfBoundsException exception is thrown if the index is negative or greater than the list size (index < 0 || index >= size()).
Code
The code below demonstrates how to use the get method.
import java.util.LinkedList;class LinkedListGetExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);System.out.println("The element at index 0 is " + list.get(0));System.out.println("The element at index 1 is " + list.get(1));System.out.println("The element at index 2 is " + list.get(2));}}
Explanation
In the code above:
- In line 1, we imported the
LinkedListclass.
import java.util.LinkedList;
- In line 4, we created a
LinkedListobject with the namelist.
LinkedList<String> list = new LinkedList<>();
- From lines 5 to 7, we used the
addmethod of thelistobject to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
- In line 10, we used the
getmethod of thelistobject to get the element at index0.
list.get(0); // "1"
- In line 11, we used the
getmethod of thelistobject to get the element at index1.
list.get(1); // "2"
- In line 12, we used the
getmethod of thelistobject to get the element at index2.
list.get(2); // "3"