Thomas Winsnes Thomas Winsnes - 4 years ago 92
Java Question

When you call remove(object o) on an arraylist, how does it compare objects?

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 objects using the interface Comparable?

Answer Source

ArrayList remove() relies on the objects implementation of the Equal method. If no implementation has been done then the object is removed by Object's implementation of Equals which indeed is the pointer comparison.

From the documentation on ArrayList -

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)

Object equal method documentation -

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download