有没有区别在集合API中的
remove(Object o)
方法(List接口)和removeFirstOccurrence(Object o)
方法(LinkedList类)之间?我可以看到两者都是删除列表中对象的第一个出现。remove(Object o)
方法(List接口)和removeFirstOccurrence(Object o)
方法(LinkedList类)之间?我可以看到两者都是删除列表中对象的第一个出现。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
我认为两者没有区别,都是删除第一次出现的元素并返回结果。更正式地说,它会删除索引最小的元素。
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;