There are
two ways to remove objects from ArrayList in Java, first, by using
remove() method, and second by using
Iterator. ArrayList provides overloaded
remove() method, one accept index of object to be removed i.e.
remove(int index), and other accept object to be removed, i.e.
remove(Object obj). Rule of thumb is, If you know index of object, then use first method, otherwise use second method. By the way, you must remember to use ArrayList remove methods, only when you are not iterating over ArrayList, if you are iterating then use
Iterator.remove() method, failing to do so may result in
ConcurrentModificationException in Java. Another gotcha can be occurred due to
autoboxing. If you look closely that two remove methods,
remove(int index) and
remove(Object obj) are indistinguishable if you are trying to remove from an
ArrayList of
Integers. Suppose you have three objects in ArrayList i.e.
[1,2,3] and you want to remove second object, which is
2. You may call
remove(2), which is actually a call to
remove(Object) if consider autoboxing, but will be interpreted as a call to remove 3rd element, by interpreting as
remove(index). I have discussed this problem earlier on my article about
best practices to follow while overloading methods in Java. Because of lesser known widening rule and autoboxing, poorly overloaded method can create lot of ambiguity.