LinkedList.remove(int) removes at a position, whereas remove(Object) removes the first equal element.
Java LinkedList remove overloads: index versus Integer value
Make the target explicit
An Integer list has two plausible meanings for remove(1). The primitive int chooses the positional overload, so the second element disappears even when its value is not one. Box the value deliberately when a business identifier must be removed by equality.
The fixture removes the element at position one, then removes a separate value. Occurrence removal covers first and last equal values; indexed traversal explains the search cost behind positional access.
Handle absence without guessing
remove(Object) returns false when no equal element exists. remove(int) throws for an invalid position. Those failure shapes should not be collapsed into the same recovery path in an API adapter.
Working program
import java.util.*;
public class DispatchIdRemoval {
public static void main(String[] args) {
LinkedList<Integer> dispatchIds = new LinkedList<Integer>(Arrays.asList(17, 23, 47));
System.out.println("position=" + dispatchIds.remove(1));
System.out.println("value=" + dispatchIds.remove(Integer.valueOf(47)));
System.out.println(dispatchIds);
}
}Output
position=23
value=true
[17]Cost and ownership
Both positional and equality-based removal may traverse O(n) nodes; unlinking a located node is constant structural work. Do not infer that a LinkedList makes arbitrary indexed deletion constant-time from the node unlink alone.
Common Mistakes
- Do not pass an int when the intended target is an Integer value.
- Do not confuse false for an absent value with IndexOutOfBoundsException for an absent index.
- Do not assume removing an arbitrary index is O(1).
Read next
Java LinkedList: operations, internals and failure cases, Java LinkedList duplicate removal: first and last occurrence, Java LinkedList indexed loops: a hidden quadratic traversal, Java ArrayList and indexed access.
