Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Thomas Winsnes Avatar asked May 24 '10 03:05

Thomas Winsnes


People also ask

What happens when you remove from an ArrayList?

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.

How do you remove an object from an ArrayList of objects?

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).

How do you compare objects in ArrayList?

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.

Does ArrayList remove use equals?

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.


1 Answers

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).

like image 54
Eric Avatar answered Oct 17 '22 13:10

Eric