List.remove(int) removes by position, while List.remove(Object) removes the first equal value.
Java List.remove with Integer: index or value
This complete Java 8 program has a checked output. Compile it as the named public class, then run it without additional libraries.
The compile-time argument type selects the overload
For List<Integer>, passing the literal 2 calls remove(int), not remove(Object). A queue of numeric receipt codes can silently delete the wrong element if that index exists. Cast to Integer or call Integer.valueOf when the intended operation is value removal.
The fixture prints both outcomes from separate lists. The first list loses the element at index two. The second loses the element whose value is two. Both operations are legal, which makes this easy to miss during review.
Check the representation cost
ArrayList shifts later references after removal; LinkedList searches for a matching value and then relinks nodes. Neither representation turns value lookup into constant time. When code needs key-based deletion at scale, a map keyed by the receipt identifier may be the better model.
Working program
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class NumericReceiptRemoval {
public static void main(String[] args) {
List<Integer> byIndex = new ArrayList<>(Arrays.asList(2, 7, 9));
byIndex.remove(2);
List<Integer> byValue = new ArrayList<>(Arrays.asList(2, 7, 9));
byValue.remove(Integer.valueOf(2));
System.out.println("index=" + byIndex);
System.out.println("value=" + byValue);
}
}Output
index=[2, 7]
value=[7, 9]Costs and boundaries
Value removal requires O(n) search in a list. ArrayList index removal may shift O(n) references; a LinkedList positional lookup also traverses O(n) nodes. The overload decision happens at compile time.
Common Mistakes
- Do not assume a numeric literal means a numeric value in remove.
- Do not use a cast to change the stored element type accidentally.
- Do not omit the absent-value behavior from an API contract.
Read next
Java ArrayList and indexed access, Java LinkedList: operations, internals and failure cases, Java HashMap: keys, collisions, and update operations.
