6

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?

5
  • Use an Integer object. Commented Mar 17, 2015 at 4:51
  • @Kon Can you give a simple example about that? Commented Mar 17, 2015 at 4:52
  • you can remove using numbers.remove(new Integer(2)); Commented Mar 17, 2015 at 4:52
  • @HaoyuChen Added it as an answer Commented Mar 17, 2015 at 4:52
  • @HaoyuChen No problem, glad to help. You may be further interested in reading about widening and boxing in Java method overloading hierarchy. It's a good thing to understand :) Commented Mar 17, 2015 at 4:56

3 Answers 3

6

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.