[JAVA] What happens when remove (int) and remove (Integer) are performed on List <Integer>?

The following methods are defined in List. ・ Remove (int index) ・ Remove (Object o)

The former is deleted by specifying the index, and the latter is deleted by specifying the object.

Now, the question is, "What will happen in the case of Integer?"

As you can see from the result, if the argument is int, the index is deleted, and if it is Integer, the object is deleted.

Although it is a common sense result, it means that "AutoBoxing should not be relied on when deleting List ".

If this bugs, I think it's a bit confusing ...

Tips0004.java


package jp.avaj.lib.algo;
import java.util.List;
import jp.avaj.lib.test.L;

public class Tips0004 {
  public static void main(String[] args) {
    Integer[] integerArray = new Integer[] {
      9,8,7,6,5,4,3,2,1,0
    };
    List<Integer> integerList;

    //Delete by index(I'm going to).
    integerList = ArArray.toList(integerArray);
    integerList.remove(8);
    L.p(ArObj.toString(integerList));

    //Delete with object(I'm going to).
    integerList = ArArray.toList(integerArray);
    integerList.remove(new Integer(8));
    L.p(ArObj.toString(integerList));
  }
}

The result is as follows.

[9, 8, 7, 6, 5, 4, 3, 2, 0]
[9, 7, 6, 5, 4, 3, 2, 1, 0]

Recommended Posts

What happens when remove (int) and remove (Integer) are performed on List <Integer>?
List of copy and paste collections that are useful when creating apps with Ruby on Rails
[Java] What are overrides and overloads?