我想在迭代数字数组时删除链接列表中存在的元素
for(int num : numbers)
{
if(l.contains(num))
{
l.remove(num);
}
}
但是,它试图删除索引 num 处的元素,而不是在链表中查找 num 。
javadoc有这个方法
remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
如何使用它?
最佳答案
你可以这样做
for(Integer num : numbers)
l.remove(num); // remove if present
这避免了与 List.remove(int index) 如果您向其传递 int 则调用和 List.remove(Object) 如果您向其传递像 Integer 这样的对象调用的混淆 em> 并避免在元素存在时扫描列表两次。
关于Java链表删除对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616312/