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

前端 未结 4 1883
借酒劲吻你
借酒劲吻你 2020-12-06 09:13

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

4条回答
  •  渐次进展
    2020-12-06 09:36

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

提交回复
热议问题