Get LinkedList elements
We can use get() method for retrieving the element from LinkedList
There are 3 different get() methods in LinkedList
1) Object get(int index);
2) Object getFirst();
3) Object getLast();
Let’s discuss these methods with example
Object get(int index)
It returns the value present at the specified index
This method throws IndexOutOfBoundsException if the index is less than zero or greater than the size of the list
Example :
- import java.util.*;
- public class LinkedListGetFromIndex {
- public static void main(String[] args) {
- LinkedList<String> list = new LinkedList<String>();
- list.add("java");
- list.add("c++");
- list.add("python");
- list.add("c");
- System.out.println("First element of the LinkedList: "+list.get(0));
- System.out.println("Third element of the LinkedList: "+list.get(2));
- }
- }
import java.util.*; public class LinkedListGetFromIndex { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.add("java"); list.add("c++"); list.add("python"); list.add("c"); System.out.println("First element of the LinkedList: "+list.get(0)); System.out.println("Third element of the LinkedList: "+list.get(2)); } }
Object getFirst()
This method returns the first element from the list
Example
- import java.util.*;
- public class LinkedListGetFirst {
- public static void main(String[] args) {
- LinkedList<String> list = new LinkedList<String>();
- list.add("java");
- list.add("c++");
- list.add("python");
- list.add("c");
- System.out.println("First element of the LinkedList: "+list.getFirst());
- }
- }
import java.util.*; public class LinkedListGetFirst { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.add("java"); list.add("c++"); list.add("python"); list.add("c"); System.out.println("First element of the LinkedList: "+list.getFirst()); } }
Object getLast()
This method returns the last element from the list
Example
- import java.util.*;
- public class LinkedListGetLast {
- public static void main(String[] args) {
- LinkedList<String> list = new LinkedList<String>();
- list.add("java");
- list.add("c++");
- list.add("python");
- list.add("c");
- System.out.println("Last element of the LinkedList: "+list.getLast());
- }
- }
import java.util.*; public class LinkedListGetLast { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.add("java"); list.add("c++"); list.add("python"); list.add("c"); System.out.println("Last element of the LinkedList: "+list.getLast()); } }