LinkedList overview
LinkedList is a doubly-linked list implementation of the List and Deque interfaces
Hence it provides linked list data structure
Important features of LinkedList
1) LinkedList maintains the insertion order similar to ArrayList
2) LinkedList contains duplicate elements
3) It’s a non-synchronized class
4) Elements can be searched in forward and backward directions
5) Searching an element takes time if the size of list is big as it has to traverse the list
6) Since it’s a doubly linked list, elements can be added/removed from both the sides
LinkedList object can be created as below
- LinkedList<String> list = new LinkedList<String>();
LinkedList<String> list = new LinkedList<String>();
Example of Linked list with some of its methods
- import java.util.*;
- public class LinkedListExample {
- public static void main(String args[]) {
- LinkedList<String> linkedlist = new LinkedList<String>();
- linkedlist.add("Welcome");
- linkedlist.add("to");
- linkedlist.add("java");
- System.out.println("Linked List -> " +linkedlist);
- linkedlist.addFirst("Hai");
- linkedlist.addLast("Bye");
- System.out.println("LinkedList after addition -> " +linkedlist);
- Object firstEle1 = linkedlist.get(0);
- System.out.println("First element: " +firstEle1);
- linkedlist.set(0, "Updated Hai");
- Object firstEle2 = linkedlist.get(0);
- System.out.println("First element after updating -> " +firstEle2);
- linkedlist.removeFirst();
- linkedlist.removeLast();
- System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
- linkedlist.add(0, "New Element");
- linkedlist.remove(2);
- System.out.println("Final linkedlist-> " +linkedlist);
- }
- }
import java.util.*; public class LinkedListExample { public static void main(String args[]) { LinkedList<String> linkedlist = new LinkedList<String>(); linkedlist.add("Welcome"); linkedlist.add("to"); linkedlist.add("java"); System.out.println("Linked List -> " +linkedlist); linkedlist.addFirst("Hai"); linkedlist.addLast("Bye"); System.out.println("LinkedList after addition -> " +linkedlist); Object firstEle1 = linkedlist.get(0); System.out.println("First element: " +firstEle1); linkedlist.set(0, "Updated Hai"); Object firstEle2 = linkedlist.get(0); System.out.println("First element after updating -> " +firstEle2); linkedlist.removeFirst(); linkedlist.removeLast(); System.out.println("LinkedList after deletion of first and last element: " +linkedlist); linkedlist.add(0, "New Element"); linkedlist.remove(2); System.out.println("Final linkedlist-> " +linkedlist); } }