Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Wednesday, September 17, 2014

LinkedList In Java: A Complete Overview

LinkedList

LinkedList is the subclass of List interface. LinkedList is an implementation of doubly linked list data structure.

LinkedList implements List as well as Serializable, and Clonable interfaces.

Few Important Points About LinkedList

  •  Underlined data structure is doubly linked list . 
  • Heterogeneous data elements are allowed.     
  • Null insertion is allowed. 
  • Duplicates are allowed. 
  • Insertion order is preserved.

     Constructor In ArrayList


LinkedList()
Constructs an empty list.

LinkedList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.



Methods In ArrayList

In addition to methods which are available in List, Collection interface, there are several LinkedList specific methods which you can be used only on LinkedList object.

  • Void addFirst(Object o) //Adds a new node at first place
  • Void addLast(Object o) //Adds a new node at last place
  • Object removeFirst() //remove and return the object at first node
  • Object removeLast() //remove and return the object at last node
  • Object getFirst() //return the object at first node
  • Object getLast() //return the object at last node

//Sample Program For LinkedList

import java.util.*;
class LinkedListDemo
 {
public static void main(String [] args)
{
LinkedList l=new LinkedList();
l.add("10");
l.add("10");
l.add(null);
l.add(1,100);
l.set(1,"DHT");
l.addFirst("10");
System.out.println(l);
}
}

Output of the above program



Scenarios When To Choose LinkedList And When Not To.

LinkedList is best choice when our main function is insertion at middle or deletion from middle. LinkedList could be worst choice if our main function is retrial of data from middle of the List.

More details:


If we want to insert new node at 2 place, we need not to perform shift operation. 


If you want to go to Node 2 of the list , it will first go to node 1 since node 1 has the address of node 2 then it will go to node 2.

Think of the same problem when we have 10 millions elements in the LinkedList and at some point if you want to retrieve some data element at 10000 position, it will have to go through 9999 nodes starting from node 1.

Retrieval of data from the middle of list is a performance violating task in LinkedList.

Read about ArrayList here



No comments: