
Java LinkedList contains the elements in the form of nodes. It is the implementation class of the List interface which uses doubly linked list store elements.
LinkedList is very convenient to store data and inserting and deleting elements in LinkedList is faster so it takes the less and same amount of time.
Table of Contents
Key points about Java LinkedList
- LinkedList preserves insertion order and also allows duplicate elements.
- null insertion is possible in LinkedList, so you can insert any number of null.
- .LinkedList in java implements Serializable and Cloneable interfaces but not RandomAccess interface.
- You can insert Homogeneous as well as Heterogeneous objects into it.
- LinkedList class is not synchronized.
When should you use LinkedList?
When your frequent operation is to add and remove items from the beginning, middle or end of the list then you should use LinkedList.
Constructors of ArrayList
LinkedList list = new LinkedList();
LinkedList list = new LinkedList(Collection c);
Note:
You can use LinkedList to implement Stacks & Queues.
Methods of Java LinkedList
Following are the basic methods that you can use to add, remove and manipulate elements in LinkedList.
Methods | Description |
boolean add(E obj) | This method adds the element to the LinkedList and if the element is added successfully then it returns true. |
void addFirst(E obj) | Adds the element at the first position. |
void addLast(E obj) | Adds the element at the last position. |
void add(int position, E obj) | Adds the elements at the specified position. |
E removeFirst() | This method returns the element from the first position and then returns it. |
E removeLast() | This method returns the element from the last position and then returns it. |
E getFirst() | Gets the element from first position. |
E getLast() | Gets the element from the last position. |
int size() | This method returns the number of elements present in the LinkedList. |
Difference between a Stack and LinkedList
The purpose of a Stack is to evaluate expressions where a LinkedList stores and retrieves data.
In a stack, insertions and deletions are possible only from the top. In case of LinkedList, it is possible to insert and delete from anywhere.
Program using Java LinkedList
import java.util.LinkedList;
public class LinkedListProgram {
public static void main(String args[]) {
LinkedList linkedList = new LinkedList();
linkedList.add("Item 1");
linkedList.add("Item 2");
linkedList.add("Item 3");
linkedList.add("Item 4");
System.out.println("LinkedList: " + linkedList);
}
}
Example of Generic LinkedList in Java
Here is the example of the generic LinkedList. If you specify a particular data type in the LinkedList then you can insert only that types of elements.
LinkedList<String> list = new LinkedList<String>();
LinkedList<Double> list = new LinkedList<Double>(30);
References:
https://docs.oracle.com/javase/7/docs/api/java/util/Lin…