当您在 arraylist 上调用 remove(object o) 时,它如何比较对象?

2022-01-25 00:00:00 compare arraylist java

当您在 java 中的 arraylist 上调用 remove(object o) 时,它如何比较对象以找到要删除的正确对象?它使用指针吗?还是使用 Comparable 接口比较对象?

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?

推荐答案

ArrayList remove() 依赖于Equal的对象实现方法.如果没有实现,则该对象被 ObjectEquals 实现移除,这确实是指针比较.

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 的文档 -

更正式地说,删除具有最低索引 i 的元素,使得 (o==null ? get(i)==null : o.equals(get(i))) (如果这样一个元素存在)

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 方法文档 -

Object equal method documentation -

Object类的equals方法实现了对象上最有区别的可能等价关系;也就是说,对于任何非空引用值 xy,当且仅当 xy 引用同一个对象(x == y 的值为 true).

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

相关文章