Java LinkedList removeLast() Method
removeLast()is in JavaLinkedLista common method provided by the class, used to remove and return the last element of the list. This method belongs tojava.util.LinkedListthe class, and is part of the Java Collections Framework.
Method Syntax:
public E removeLast()
Return Value:
- Returns the last element that was removed
- If the list is empty, throws
NoSuchElementException
Method Characteristics
1. Operation Position
removeLast()The method specifically operates on the tail of the list, which isremoveFirst()in contrast to the method.
2. Time Complexity
SinceLinkedListis a doubly linked list implementation,removeLast()the time complexity of the method is O(1), because the tail node can be accessed directly.
3. Exception Cases
Calling this method when the list is empty will throwNoSuchElementException, so it is usually necessary to check whether the list is empty before use.
Usage Example
Below is a complete example code showing how to useremoveLast()method:
Example
public class LinkedListDemo {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> fruits = new LinkedList<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
System.out.println("Original LinkedList: " + fruits);
// Use the removeLast() method
String removedElement = fruits.removeLast();
System.out.println("Removed element: " + removedElement);
System.out.println("LinkedList after operation: " + fruits);
}
}
Output:
原始链表: [Apple, Banana, Cherry, Date] 被移除的元素: Date 操作后的链表: [Apple, Banana, Cherry]
Comparison with Other Methods
1. removeLast() vs removeFirst()
removeLast()Remove and return the last elementremoveFirst()Remove and return the first element
2. removeLast() vs pollLast()
- Both remove and return the last element
- The main difference lies in the behavior when the list is empty:
removeLast()Throws an exceptionpollLast()Returns null
3. removeLast() vs pop()
pop()What is actually called isremoveFirst(), and what is removed is the first elementremoveLast()removes the last element
Best Practices
1. Empty List Check
To avoid `NoSuchElementException`, it is recommended to check whether the list is empty before use:Example
myLinkedList.removeLast();
}
2. Alternative Approaches
If you don't want to handle exceptions, you can usepollLast()method:
Example
String lastElement = myLinkedList.pollLast();
3. Performance Considerations
SinceLinkedListofremoveLast()the operation is constant time, suitable for frequent tail removal operations. If the scenario involves more random access, consider usingArrayList。
Summary
LinkedList.removeLast()is an efficient method, specifically used to remove elements from the tail of a linked list. Understanding the behavioral characteristics of this method and its differences from other similar methods can help developers more effectively useLinkedListthe class.
Java LinkedList