Java program to access elements from a linkedlist.
Here's an example Java program that demonstrates how to access elements from a LinkedList
:
import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // Create a LinkedList LinkedList<String> list = new LinkedList<>(); // Add elements to the LinkedList list.add("Apple"); list.add("Banana"); list.add("Cherry"); list.add("Date"); list.add("Elderberry"); // Access elements by index System.out.println("Element at index 0: " + list.get(0)); System.out.println("Element at index 2: " + list.get(2)); // Access the first and last elements System.out.println("First element: " + list.getFirst()); System.out.println("Last element: " + list.getLast()); // Iterate over the elements in the LinkedList System.out.println("Iterating over the LinkedList:"); for (String element : list) { System.out.println(element); } } }ww:ecruoSw.theitroad.com
In this example, we first create a LinkedList
of strings and add some elements to it using the add()
method.
To access elements in the LinkedList
, we can use the get()
method, which takes an index as an argument and returns the element at that index.
We can also access the first and last elements of the LinkedList
using the getFirst()
and getLast()
methods.
To iterate over the elements in the LinkedList
, we can use a for-each loop. This will loop through each element in the LinkedList
and print it to the console.