Java Linkedlist Examples

Java Linkedlist implement the List and deque interface. It is use doubly linkedlist to store the data. It is maintain insertion order of element.It alllow to store duplicate value including null value. In Previous post we have Learn Arraylist used dynamic array to store data, But linkedlist use doubly linkedlist to store data. Linkedlist provide predefined method for difference functionalities.

Hierarchy of LinkedList class in Java

The LinkedList class extends AbstractSequentialList and implements the List,Deque, and Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this declaration:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
//there is code 
}

Here, E specifies the type of objects that the list will store

Hierarchy of LinkedList class in Java
Hierarchy of LinkedList class in Java

LinkedList Features In Java

  • Inherits – Linkedlist inherits AbstractList class and implements List interface.
  • Implementation – it is dobuly linkedlist imlemention use for store data.
  • Ordered – Linkedlist Elements maintain insertion ordered .
  • Non synchronized – Linkedlist is not synchronized, by default..
  • Duplicates allowed – We can add duplicate elements in linkedlist.
  • Null value – Linkedlist can store null values.
  • Manipulation – Linkedlist perform manipulation operation fast as compare of arraylist beacause in linkedlist there is no shift operation.
  • Wrapper class – Linkedlist can not be used for primitive types, like int,float, char, etc. We need a wrapper class for linkedlist.

Why Linkedlist is better than Array?

  • Array is fixed in size in and linkedlist can grow dynamically . Mostly we don’t know size of data in that case linkedlist is better option then array.
  • Array need  contiguous memory allocation for store data. But linked list create new node whenever needed.
  • Inserting an element in array is costly because when you insert a element in middle or start we need to shift other element.But in case linkedlist it updated pointer of node.
  • Linkedlist have may predefined method for different functionalities ,these function are very optimize in term of performance , array does not have such methods.

How to create an ArrayList?

We can create linkedlist using these Constructor .                                                            LinkedList() – Constructs an empty list.
LinkedList(Collection<? extends E> c) – Constructs a list containing the elements of the given collection, in the order they are returned by the collection’s iterator.

Let’s try these stuff by coding

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LinkedListExample {
	public static void main(String[] args) {
		List<String> linkedlist = new LinkedList<String>();
		linkedlist.add("java");
		linkedlist.add("php");
		linkedlist.add("mysql");
		System.out.println("linkedlist is ="+linkedlist);
		
		List<String> list = new ArrayList<String>();
		list.add("amit");
		list.add("shubham");
		list.add("shivam");
		//create linkedlist from arraylist
		List<String> linkedlistFromCollection = new LinkedList<String>(list);
		System.out.println("linked from collection ="+linkedlistFromCollection);
	}

}

Output :

linkedlist is =[java, php, mysql]
linked from collection =[amit, shubham, shivam]

Add elements to a LinkedList

Now we will add new element in linkedlist useing add() method . Here we will add element using add(),add(index,eleement) , addFirst() and addLast(). let’s try code for that.

import java.util.LinkedList;
import java.util.List;

public class LinkedlistAdd {
	public static void main(String[] args) {
		List<String> linkedlist = new LinkedList<String>();
		
		//adding element using add(Element e) method in linkedlist
		linkedlist.add("java");
		linkedlist.add("php");
		linkedlist.add("mysql");
		System.out.println("linkedlist is ="+linkedlist);
		
		//adding element on 2 position in linkedlist 
		linkedlist.add( 1 ,"spring");		
		System.out.println("linked list after adding element on second 
                postion ="+ linkedlist);
		
		//adding element fist of list
		linkedlist.addFirst("html");
		
		//adding element add last of list
		lnkedlist.addLast("angular");
		
		System.out.println("final list ="+ linkedlist);
	
		
	}

}

Output :

linkedlist is =[java, php, mysql]
linked list after adding element on second postion =[java, spring, php, mysql]
final list =[html,java, spring, php, mysql,angular]

Retrieving elements from a LinkedList

We can retrieve element from linked using get() method.Here we will retrieve element as

  • Get element from given index
  • Get element from first of list.
  • Get element from last of list.

Now we can understand these operation by code

import java.util.LinkedList;
import java.util.List;

public class LinkedlistGet {
	public static void main(String[] args) {
		List<String> linkedlist = new LinkedList<String>();
		
		//adding element using add(Element e) method in linkedlist
		linkedlist.add("java");
		linkedlist.add("php");
		linkedlist.add("mysql");
		//displaying list
		System.out.println("linkedlist is ="+linkedlist);
        //retrived element from index 1
		System.out.println("Element from 1 index ="+ linkedlist.get(1));
		//retrive first element from  list
		System.out.println("first element from list ="+ linkedlist.getFirst());
		
		//retrived last element from  list 
		System.out.println("last element from list ="+ linkedlist.getLast());
		
	}

}

Output :

linkedlist is =[java, php, mysql]
Element from 1 index =php
first element from list =java
last element from list = mysql

Removing elements from a LinkedList

We can remove element from linkedlist as follow

  • Remove element from given index
  • Remove first element from given list.
  • Remove last element from given list.
import java.util.LinkedList;
import java.util.List;

public class LinkedlistRemove {
	public static void main(String[] args) {
		List<String> linkedlist = new LinkedList<String>();
		
		//adding element using add(Element e) method in linkedlist
		linkedlist.add("java");
		linkedlist.add("php");
		linkedlist.add("mysql");
		linkedlist.add("html");
		linkedlist.add("android");
		
		//displaying list
		System.out.println("linkedlist is ="+linkedlist);
		
		//remove element from index 1
		linkedlist.remove(1);
		System.out.println("after remove element from index 1 ="+ linkedlist);
		
		//removing first element form list
		//linkedlist.removeFirst();
		System.out.println("after remove first  element="+ linkedlist);
		
		//removing last element from list
		//linkedlist.removeLast();
		System.out.println("after remove last element="+ linkedlist);
		
	}

}

Output :

linkedlist is =[java, php, mysql, html, android]
after remove element from index 1 =[java, mysql, html, android]
after remove first  element=[mysql, html, android]
after remove last element=[mysql, html]

Iterating over an LinkedList

import java.util.Iterator;

import java.util.LinkedList;

public class LinklistIterator {

public static void main(String[] args) {

LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add(“Mumbai”);
linkedList.add(“Delhi”);
linkedList.add(“Noida”);
linkedList.add(“Gao”);
linkedList.add(“Patna”);

Iterator<String>  itr = linkedList.iterator();
while (itr.hasNext()) {
System.out.println(“Element is =”+itr.next());
  }
}
}

Output :

Element is =Mumbai
Element is =Delhi
Element is =Noida
Element is =Gao
Element is =Patna

Change Elements of a LinkedList

Linkedlist  provide set(index,element) method for change the element value of given index . let’s try to understand set() method by code as below.

import java.util.LinkedList;
import java.util.List;

public class LinkedlistChangeElement {
	public static void main(String[] args) {
		List<String> linkedlist = new LinkedList<String>();
		
		//adding element using add(Element e) method in linkedlist
		linkedlist.add("java");
		linkedlist.add("php");
		linkedlist.add("mysql");
		linkedlist.add("html");
		linkedlist.add("android");

		//displaying element of list
		System.out.println("linkedlsit is ="+ linkedlist);
		
		//change 1 index element of linkedlist
		linkedlist.set(1, "python");
		
		//displying element of list after changing element of index 1
		System.out.println("after changing element ="+ linkedlist);
		
	}
}

output:

linkedlsit is =[java, php, mysql, html, android]
after changing element =[java, python, mysql, html, android]

Methods of LinkedList class:

  1. add(E e) – This method appends the given element to the end of this list.
  2. add(int index, E element) – This method Inserts the given element at the specified position in this list.
  3. addAll(Collection<? extends E> c) – This method appends all of the elements in the given collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
  4. addAll(int index, Collection<? extends E> c) : This method inserts all of the elements in the specified collection into this list, starting at the specified position.
  5. addFirst(E e) : This method inserts the specified element at the beginning of this list.
  6. addLast(E e) : This method appends the specified element to the end of this list.
  7. clear() : It removes all of the elements from this list.
  8. clone() : This method returns a shallow copy of this LinkedList.
  9. contains(Object o) : It returns true if this list contains the specified element.
  10. get(int index) : This method returns the element at the specified position in this list.
  11. getFirst() : It returns the first element in this list.
  12. getLast() : It returns the last element in this list.
  13. remove() – It retrieves and removes the head (first element) of this list.
  14. remove(int index) – It removes the element at the specified position in this list.
  15. remove(Object o) – It removes the first occurrence of the specified element from this list, if it is present
  16. removeFirst() – It removes and returns the first element from this list.
  17. removeFirstOccurrence(Object o) – It removes the first occurrence of the specified element in this list (when traversing the list from head to tail).
  18. set(int index, E element) – It replaces the element at the specified position in this list with the specified element.
  19. toArray() – It returns an array containing all of the elements in this list in proper sequence (from first to last element).
  20. indexOf(Object o) : This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
  21. lastIndexOf(Object o) : This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
  22. offer(E e) : It adds the specified element as the tail (last element) of this list.
  23. peek() : It retrieves, but does not remove, the head (first element) of this list.
  24. poll() : It retrieves and removes the head (first element) of this list.
  25. pop() : It pops an element from the stack represented by this list.
  26. push(E e) :It pushes an element onto the stack represented by this list.

LinkedList Tutorials

 

Leave a Reply

Your email address will not be published. Required fields are marked *

9 + 1 =