LinkedList get() Method in Java
Last Updated :
16 Dec, 2024
Improve
In Java, the get() method of LinkedList is used to fetch or retrieve an element at a specific index from a LinkedList.
Example 1: Here, we use the get() method to retrieve an element at a specified index.
// Java Program to illustrate get() method
import java.util.LinkedList;
public class Geeks {
public static void main(String[] args) {
// Creating an empty LinkedList
LinkedList<String> l = new LinkedList<>();
// Use add() method to add
// elements in the list
l.add("Geeks");
l.add("for");
l.add("Geeks");
l.add("10");
System.out.println("" + l);
// Fetching the specific element from the list
System.out.println("The element at index 3 is: "
+ l.get(3));
}
}
Output
[Geeks, for, Geeks, 10] The element at index 3 is: 10
Syntax of Java LinkedList get() Method
public E get(int index)
- Parameter: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList.
- Return type: It return the element at the specified index.
- Exception: It throws IndexOutOfBoundsException if the index is out of range (index < 0 or index >= size).
Example 2: Here, the get() method throw an exception IndexOutOfBoundsException, if we try to retrieve the element at an Invalid Index.
// Throws IndexOutOfBoundsException
import java.util.LinkedList;
public class Geeks {
public static void main(String[] args) {
// Creating an Empty LinkedList
LinkedList<Integer> l = new LinkedList<>();
// Use add() to insert
// elements in the list
l.add(10);
l.add(20);
l.add(30);
// Trying to get an element
// at an invalid index
try {
int a = l.get(5);
}
catch (IndexOutOfBoundsException e) {
System.out.println(
"Error: IndexOutOfBounds");
}
}
}
Output
Error: IndexOutOfBounds