removeFirstOccurrence和remove之间的区别是什么?

3
有没有区别在集合API中的remove(Object o)方法(List接口)和removeFirstOccurrence(Object o)方法(LinkedList类)之间?我可以看到两者都是删除列表中对象的第一个出现。
3个回答

2
没有,没有任何区别。
如果你查看removeFirstOccurrence()的源代码,你会发现:
public boolean removeFirstOccurrence(Object o) {
    return remove(o);
}
< p > LinkedList 同时具有这两个方法的原因在于每个方法的 javadoc 中都有说明:

remove(Object o)
在接口 Collection<E> 中被指定为:remove
在接口 Deque<E> 中被指定为:remove
在接口 List<E> 中被指定为:remove

removeFirstOccurrence(Object o)
在接口 Deque<E> 中被指定为:removeFirstOccurrence


2
在集合框架中,List接口的remove(Object o)方法和LinkedList类的removeFirstOccurrence(Object o)方法有什么区别吗?
这是两个不同的方法,来自于两个不同的接口。 第一个方法(remove(Object o))在java.util.Collection接口中定义。 另一个方法(removeFirstOccurrence(Object o))在java.util.Deque接口中定义。
第一个方法(remove(Object o))在Collection接口中具有相当通用的契约:
从该集合中删除指定元素的单个实例,如果存在...
但继承Collection的List接口具有更具体的契约:
从此列表中删除指定元素的第一次出现(可选操作),如果存在....
另一方面,在Deque接口中定义的removeFirstOccurrence(Object o)指定了类似的契约:
从此deque中删除指定元素的第一次出现...
事实证明,LinkedList直接实现List和Deque。由于List.remove(Object o)和Deque.removeFirstOccurrence(Object o)指定了相似的契约,因此LinkedList类中这两种方法的行为和实现是相同的。

0

我认为两者没有区别,都是删除第一次出现的元素并返回结果。更正式地说,它会删除索引最小的元素。

Java API ArrayList remove。

  public boolean remove(Object o) {
            if (o == null) {
                for (int index = 0; index < size; index++)
                    if (elementData[index] == null) {
                        fastRemove(index);
                        return true;
                    }
            } else {
                for (int index = 0; index < size; index++)
                    if (o.equals(elementData[index])) {
                        fastRemove(index);
                        return true;
                    }
            }
            return false;
        }

链表 removeFirstOccurrence

if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接