Haoyu Chen
Haoyu Chen

Reputation: 1810

Ambiguity of Remove Method in Java ArrayList

Generally, the usage of remove method for ArrayList in Java is shown as below:

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("efg");

list.remove(1);   //Removing the second element in ArrayList.
list.remove("abc");  //Removing the element with the value "abc" in ArrayList. 

However, there is situation where overloading doesn't work.

ArrayList<Integer> numbers = new ArrayList<Integer>();

numbers.add(1); numbers.add(2); when I tried to remove the element with value 2. It gives me error:

java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.remove(ArrayList.java:387)

So it looks like when it comes to remove number, I can't remove element with specific value. Because the computer would assume all the integer value as index, not the value of element.

It is a subtle error. Is there any other simple way to delete the element with specific integer value?

Upvotes: 6

Views: 947

Answers (3)

Vladimir Yudin
Vladimir Yudin

Reputation: 9

Normally you are not removing a hardcoded number, but a variable value. Therefore it is better to use Integer.valueOf(yourIntVar). This way you use an existing object rather than creating a new one.

Upvotes: 0

shikjohari
shikjohari

Reputation: 2288

Try remove(new Integer(1). This will work as it ll be a exact match to remove(Object o)

Upvotes: 1

Kon
Kon

Reputation: 10810

You need to use an Integer object.

    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(10);
    numbers.remove(new Integer(5));
    System.err.println(numbers);
    //Prints [10]

Upvotes: 6

Related Questions