Java - LinkedList Methods Part 3: Removing Elements
The LinkedList provides several methods to remove elements: remove(), removeFirst(), removeLast(), and more.
Examples and Explanation
Using remove()
list.remove("Elderberry");
System.out.println(list); // Output: [Cherry, Apple, Banana, Date, Fig, Grape]
Explanation: Removes the first occurrence of the specified element.
Using removeFirst()
list.removeFirst();
System.out.println(list); // Output: [Apple, Banana, Date, Fig, Grape]
Explanation: Removes the first element, often used in queue operations.
Using removeLast()
list.removeLast();
System.out.println(list); // Output: [Apple, Banana, Date, Fig]
Explanation: Removes the last element, useful for stack operations.
Removing by Index
list.remove(1);
System.out.println(list); // Output: [Apple, Date, Fig]
Explanation: Removes the element at the specified index, shifting subsequent elements.
Clearing the Entire List
list.clear();
System.out.println(list); // Output: []
Explanation: Clears all elements, resetting the LinkedList.