0

I want to remove the element if it is present in a linkedlist while iterating over an array of numbers

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

However, it is trying to remove element at index num, instead of looking for num in the linked list.

The javadoc has this method

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

How to use it?

showdev
  • 28,454
  • 37
  • 55
  • 73
user2133404
  • 1,816
  • 6
  • 34
  • 60

4 Answers4

5

You can do this instead

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

This avoids the confusion with List.remove(int index) called if you pass it an int and List.remove(Object) called if you pass it an object like Integer and avoids scanning the list twice if the element is present.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

You should box it in an Integer like this:

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

or iterate over Integer objects instead of ints.

AJMansfield
  • 4,039
  • 3
  • 29
  • 50
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
1

I would instead just do this:

l.removeAll(Arrays.asList(numbers));
AJMansfield
  • 4,039
  • 3
  • 29
  • 50
0

You will need to call remove(Object): invocation of remove(num) is not matching with the function with signature remove(Object o) where the function parameter is of reference type. instead it matches with remove(int index).

Hence, invoking remove(Integer.valueOf(num)) will work as it will pass a reference type.

AJMansfield
  • 4,039
  • 3
  • 29
  • 50
Sage
  • 15,290
  • 3
  • 33
  • 38