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?
If you call ArrayList. remove() the element at the given index is removed from the list (and all elements following it move down one index). The object itself still exists, no memory has been freed yet.
There are two ways to remove objects from ArrayList in Java, first, by using the remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accepts the index of the object to be removed i.e. remove(int index), and the other accept objects to be removed, i.e. remove(Object obj).
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
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.
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
andy
, this method returns true if and only ifx
andy
refer to the same object (x == y
has the valuetrue
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With