Properly removing an Integer from a List<Integer>

JavaCollectionsOverloading

Java Problem Overview


Here's a nice pitfall I just encountered. Consider a list of integers:

List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(6);
list.add(7);
list.add(1);

Any educated guess on what happens when you execute list.remove(1)? What about list.remove(new Integer(1))? This can cause some nasty bugs.

What is the proper way to differentiate between remove(int index), which removes an element from given index and remove(Object o), which removes an element by reference, when dealing with lists of integers?


The main point to consider here is the one @Nikita mentioned - exact parameter matching takes precedence over auto-boxing.

Java Solutions


Solution 1 - Java

Java always calls the method that best suits your argument. Auto boxing and implicit upcasting is only performed if there's no method which can be called without casting / auto boxing.

The List interface specifies two remove methods (please note the naming of the arguments):

  • remove(Object o)
  • remove(int index)

That means that list.remove(1) removes the object at position 1 and remove(new Integer(1)) removes the first occurrence of the specified element from this list.

Solution 2 - Java

You can use casting

list.remove((int) n);

and

list.remove((Integer) n);

It doesn't matter if n is an int or Integer, the method will always call the one you expect.

Using (Integer) n or Integer.valueOf(n) is more efficient than new Integer(n) as the first two can use the Integer cache, whereas the later will always create an object.

Solution 3 - Java

I don't know about 'proper' way, but the way you suggested works just fine:

list.remove(int_parameter);

removes element at given position and

list.remove(Integer_parameter);

removes given object from the list.

It's because VM at first attempts to find method declared with exactly the same parameter type and only then tries autoboxing.

Solution 4 - Java

list.remove(4) is an exact match of list.remove(int index), so it will be called. If you want to call list.remove(Object) do the following: list.remove((Integer)4).

Solution 5 - Java

> Any educated guess on what happens when you execute list.remove(1)? What about list.remove(new Integer(1))?

There is no need to guess. The first case will result in List.remove(int) being called, and the element at position 1 will be removed. The second case will result in List.remove(Integer) being called, and the element whose value is equal to Integer(1) will be removed. In both cases, the Java compiler selects the closest matching overload.

Yes, there is potential for confusion (and bugs) here, but it is a fairly uncommon use-case.

When the two List.remove methods were defined in Java 1.2, the overloads were not ambiguous. The problem only arose with the introduction of generics and autoboxing in Java 1.5. In hind-sight, it would have been better if one of the remove methods had been given a different name. But it is too late now.

Solution 6 - Java

Note that even if the VM did not do the right thing, which it does, you could still ensure proper behaviour by using the fact that remove(java.lang.Object) operates on arbitrary objects:

myList.remove(new Object() {
  @Override
  public boolean equals(Object other) {
    int k = ((Integer) other).intValue();
    return k == 1;
  }
}

Solution 7 - Java

Simply I did like following as suggested by #decitrig in accepted answer first comment.

list.remove(Integer.valueOf(intereger_parameter));

This helped me. Thanks again #decitrig for your comment. It may help for some one.

Solution 8 - Java

Well here is the trick.

Let's take two examples here:

public class ArrayListExample {

public static void main(String[] args) {
    Collection<Integer> collection = new ArrayList<>();
    List<Integer> arrayList = new ArrayList<>();

    collection.add(1);
    collection.add(2);
    collection.add(3);
    collection.add(null);
    collection.add(4);
    collection.add(null);
    System.out.println("Collection" + collection);

    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(null);
    arrayList.add(4);
    arrayList.add(null);
    System.out.println("ArrayList" + arrayList);

    collection.remove(3);
    arrayList.remove(3);
    System.out.println("");
    System.out.println("After Removal of '3' :");
    System.out.println("Collection" + collection);
    System.out.println("ArrayList" + arrayList);

    collection.remove(null);
    arrayList.remove(null);
    System.out.println("");
    System.out.println("After Removal of 'null': ");
    System.out.println("Collection" + collection);
    System.out.println("ArrayList" + arrayList);

  }

}

Now let's have a look at the output:

Collection[1, 2, 3, null, 4, null]
ArrayList[1, 2, 3, null, 4, null]

After Removal of '3' :
Collection[1, 2, null, 4, null]
ArrayList[1, 2, 3, 4, null]

After Removal of 'null': 
Collection[1, 2, 4, null]
ArrayList[1, 2, 3, 4]

Now let's analyze the output:

  1. When 3 is removed from the collection it calls the remove() method of the collection which takes Object o as parameter. Hence it removes the object 3. But in arrayList object it is overridden by index 3 and hence the 4th element is removed.

  2. By the same logic of Object removal null is removed in both cases in the second output.

So to remove the number 3 which is an object we will explicitly need to pass 3 as an object.

And that can be done by casting or wrapping using the wrapper class Integer.

Eg:

Integer removeIndex = Integer.valueOf("3");
collection.remove(removeIndex);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuval AdamView Question on Stackoverflow
Solution 1 - JavaakaView Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaNikita RybakView Answer on Stackoverflow
Solution 4 - JavaPetar MinchevView Answer on Stackoverflow
Solution 5 - JavaStephen CView Answer on Stackoverflow
Solution 6 - Javauser268396View Answer on Stackoverflow
Solution 7 - JavaShailendra MaddaView Answer on Stackoverflow
Solution 8 - JavaPritam BanerjeeView Answer on Stackoverflow