In Java, a LinkedList is a data structure that stores a collection of elements in a sequence.
It is similar to an array but has the advantage of dynamic size and efficient insertion and deletion of elements.
To access elements from a LinkedList, you can use the get() method provided by the LinkedList class.
The get() method returns the element at a specified index in the LinkedList.
Here’s a simple Java program that demonstrates how to access elements from a LinkedList:
import java.util.LinkedList; public class AccessLinkedListElements { public static void main(String[] args) { // Create a LinkedList of integers LinkedList<Integer> numbers = new LinkedList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40); numbers.add(50); // Access elements using the get() method System.out.println("Element at index 0: " + numbers.get(0)); System.out.println("Element at index 2: " + numbers.get(2)); System.out.println("Element at index 4: " + numbers.get(4)); } }
In the above program, we first create a LinkedList of integers and add some elements to it.
Then, we use the get() method to access the elements at index 0, 2, and 4 and print them to the console.
Output:
Element at index 0: 10 Element at index 2: 30 Element at index 4: 50
Note that the get() method throws an IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).
Therefore, you should always check the size of the LinkedList before accessing its elements using the get() method.
In conclusion, accessing elements from a LinkedList in Java is straightforward.
You can use the get() method to access the elements at a specified index.