Java LinkedList Methods
In Java, LinkedList is a part of the Collection Framework. It is used to store elements in a sequence. Unlike ArrayList, LinkedList stores elements in nodes, where each node contains data and a reference to the next node.
LinkedList belongs to the java.util package. So we need to import it before using it.
1. Importing LinkedList
import java.util.LinkedList;
2. Creating a LinkedList
LinkedList list = new LinkedList();
Here, String is the data type stored in the LinkedList.
3. add()
The add() method adds elements to the LinkedList.
list.add("Apple");
list.add("Banana");
list.add("Mango");
System.out.println(list);
4. addFirst() and addLast()
addFirst() adds an element at the beginning.
addLast() adds an element at the end.
list.addFirst("Orange");
list.addLast("Grapes");
System.out.println(list);
5. get()
The get() method returns the element at a specific index.
System.out.println(list.get(0));
6. getFirst() and getLast()
getFirst() returns the first element.
getLast() returns the last element.
System.out.println(list.getFirst());
System.out.println(list.getLast());
7. set()
The set() method changes the element at a specific index.
list.set(1, "Pineapple");
System.out.println(list);
8. remove()
The remove() method removes an element by index or by value.
list.remove(0); // remove by index
list.remove("Mango"); // remove by value
System.out.println(list);
9. removeFirst() and removeLast()
removeFirst() removes the first element.
removeLast() removes the last element.
list.removeFirst();
list.removeLast();
System.out.println(list);
10. size()
The size() method returns the number of elements.
System.out.println(list.size());
11. contains()
The contains() method checks whether an element exists in the LinkedList.
System.out.println(list.contains("Apple"));
12. clear()
The clear() method removes all elements from the LinkedList.
list.clear();
System.out.println(list);
13. isEmpty()
The isEmpty() method checks if the LinkedList is empty.
System.out.println(list.isEmpty());
LinkedList as Queue
LinkedList can also work as a queue.
LinkedList queue = new LinkedList();
queue.add("A");
queue.add("B");
queue.add("C");
System.out.println(queue.poll()); // removes first element
System.out.println(queue.peek()); // shows first element
Difference Between ArrayList and LinkedList
- LinkedList uses nodes to store data.
- Insertion and deletion are faster in LinkedList.
- ArrayList is better for accessing elements by index.
- LinkedList uses more memory than ArrayList.
Conclusion
The LinkedList class provides many useful methods like add(), remove(), get(), set(), addFirst(), removeLast(), and more.
It is useful when you need frequent insertion and deletion operations.
Tip: Use LinkedList when your program requires frequent data insertion or removal.