LinkedList in Java are a better alternative to Arrays, and provides almost all functionality that a ArrayList provides. LinkedList uses a doubly LinkedList to store and navigate the elements. This means that each element in the List contains the address of previous element as well as the next element. Thus navigating back and froth in List becomes easier.
- LinkedList should be opted when there are frequent insertion and deletion in your List.
Creating and Navigating a LinkedList
import java.util.Iterator; import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // Creating a LinkedList LinkedList<String> stationList = new LinkedList<String>(); // Adding Elements to a LinkedList stationList.add("Mumbai"); stationList.add("Delhi"); stationList.add("Banglore"); stationList.add("Pune"); // Navigating a Linked List for (int i = 0; i < stationList.size(); i++) { System.out.println("Station " + i + " is " + stationList.get(i)); } // Removing Element from LinkedList stationList.remove(2); // Navigating LinkedList with an Iterator Iterator<String> it = stationList.iterator(); int i = 0; while (it.hasNext()) { i++; System.out.println("Station " + i + " is " + it.next()); } } }
The above example code shows Creating a LinkedList, Adding and Removing an Element to a LinkedList and Iterating over a LinkedList.
As you can see the functionality is exactly same as ArrayList. But there is a significant different in the performance of the two when there is a Large List in the operation.
While Inserting a new Element in between of a LinkedList , It has just to do some address changes for the previous and next Elements. In Case of ArrayList , if there is a List of 1000 Items and we are inserting a new Element at 10th Position then there will be shifting operation of all the 990 Elements after 10th.