2013-12-16 72 views
0

我要删除的元素,如果它是存在于链表而迭代数的数组爪哇链接列表中删除对象的方法

for(int num : numbers) 
{ 
    if(l.contains(num)) 
    { 
     l.remove(num); 
    } 
} 

但是,它试图而不是在索引NUM去除元件,在链表中寻找数字。

的Javadoc有这个方法

remove(Object o) 
Removes the first occurrence of the specified element from this list, if it is present. 

如何使用它?

+4

使用'l.remove(新的整数(NUM));' –

+0

另外,不要使用'为each'。 – MikeTheLiar

+0

谢谢,它的工作。 那是因为如果我们使用一个原始类型,它需要它的索引?所以我们把它包装为对象? – user2133404

回答

5

你可以做到这一点,而不是

for(Integer num : numbers) 
    l.remove(num); // remove if present 

这避免了List.remove(INT指数)混乱如果你传递一个int和List.remove(对象)呼吁,如果你通过它叫像Integer这样的对象,并避免在元素存在时两次扫描列表。

+0

@AJMansfield,有什么问题? –

+0

哦,好的。感谢您的答复。 –

+0

@ user503413实际上现在我认为还有更多,这根本不是问题。 – AJMansfield

0

您需要致电remove(Object)remove(num)的调用与签名为remove(Object o)的函数不匹配,其中函数参数为参考类型。相反它与remove(int index)匹配。

因此,调用remove(Integer.valueOf(num))将工作,因为它会通过引用类型。

1

你应该框它在Integer这样的:

l.remove(Integer.valueOf(num));

或迭代Integer对象,而不是int秒。

1

我反而只是这样做:

l.removeAll(Arrays.asList(numbers));