LinkedList in Java
Advertisements
LinkedList class in Java
A LinkedList is a Collection of nodes. LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.
Hirerachy of LinkedList
Important points LinkedList
- A LinkedList is a Collection of nodes.
- LinkedList class is not Synchronized.
- LinkedList class can contain duplicate elements.
- LinkedList organize the data in the form of nodes.
Constructor of LinkedList
- LinkedList(): is used for creating an object of LinkedList without specifying any number of nodes.
- LinkedList(int): is used for creating an object of ll by specifying the initial number of nodes to be created.
Syntax
LinkedList ll=new LinkedList();
Here ll represent object name and it can be treated as Collection framework variable and it allows us to store multiple values either of same type or different type or both the types.
Methods of LinkedList
- public void addFirst(Object): are used for adding the elements at first position of LinkedList.
- public void addLast(Object): are used for adding the elements at last position of LinkedList.
- public Object getFirst(): are used for get first position elements of LinkedList.
- public Object getLast(): are used for get last position elements of LinkedList.
- public Object removedFirst(): are used for remove first position elements of LinkedList.
- public Object removedLast(): are used for remove last position elements of LinkedList.
Advantages of LinkedList
- LinkedList class object allows us to organize the data and it may belong to both homogeneous or heterogeneous elements.
- LinkedList class object contains dynamic size in nature.
- LinkedList class object allows us to insert the data either in the beginning or in the ending or in the middle (dynamic insertion are allowed).
Limitations of LinkedList
- LinkedList class object takes more memory space (explicitly) memory space is created for Data part and Address part in heap memory.
- LinkedList class object takes more retrieval time(after processing data of the current node,to process the data of next node,internally JVM will reterive address of next node from address part of current node which is one of the consuming process.).
- Less performance:
To avoid the problems of LinkedList we use the concept of ArrayList. Because ArrayList class developed by Sun developers by making use of associative memory.
Note: If we store anything in associative memory which will take negligible amount of space and if we retrieve anything from associative memory than it will take negligible amount of time.
Example of LinkedList
import java.util.*; class LinkedListDemo { public static void main(String[] args) { LinkedList<Integer> ll=new LinkedList<Integer>(); // Add content ll.add(20); ll.add(30); ll.add(40); ll.add(50); Iterator itr=ll.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } }
Output
20 30 40 50
Google Advertisment