Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList.
1. We can use get(int variable) method to access an element from a specific index of LinkedList:
In the given example, we have used the get(i) method. Here, the method returns the element which is at the i th index.
Parameters: The parameter index is of integer data type that specifies the position or index of the element to be fetched from the LinkedList.
Return Value: The method returns the element present at the position specified by the parameter index.
LinkedList Elements : Element at index 0 is: GEEKS Element at index 1 is: FOR Element at index 2 is: GEEKS
2. We can use the iterator() method
- To use this method we have to import java.util.Iterator package.
- In this method, we can iterate over the LinkedList and then extract the element at the given index accordingly.
The elements of the input LinkedList: The element at the index 0 GEEKS The element at the index 1 FOR The element at the index 2 GEEKS
3. We can use ListIterator() method.
- ListIterator() is a subinterface of Iterator() method.
- It provides us with the function to access the elements of a list.
- It is bidirectional that means it allows us to iterate elements of a list in the both the direction.
- To use this method we have to import java.util.ListIterator.
The elements of the LinkedList: The element at the index 0 GEEKS The element at the index 1 FOR The element at the index 2 GEEKS The elements of the LinkedList in Reverse order: The element at the index 2 GEEKS The element at the index 1 FOR The element at the index 0 GEEKS
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.