When you call remove(object o) on an arraylist in java, how does it compare the objects to find the correct one to remove? does it use the pointer? or does it compare the ob
You should always consult the API for this kind of information.
ArrayList.remove(Object o): Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index
i
such that(o==null ? get(i)==null : o.equals(get(i)))
(if such an element exists).
Perhaps you were confusing this with e.g. TreeSet
:
java.util.TreeSet: Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the
Set
interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because theSet
interface is defined in terms of theequals
operation, but aTreeSet
instance performs all element comparisons using itscompareTo
(orcompare
) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.
(Unfortunately e.g. TreeSet.remove method itself doesn't have any explicit reminder of the above caveat, but at least it's prominently placed at the top of the class documentation)
The following snippet illustrates the difference in behaviors between collections that use equals
(such as an ArrayList
) and collections that use compare/compareTo
(such as a TreeSet
).
import java.util.*;
public class CollectionEqualsCompareTo {
static void test(Collection