Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguity of Remove Method in Java ArrayList

Tags:

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?

like image 312
Haoyu Chen Avatar asked Mar 17 '15 04:03

Haoyu Chen


2 Answers

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]
like image 119
Kon Avatar answered Sep 27 '22 17:09

Kon


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

like image 37
shikjohari Avatar answered Sep 27 '22 17:09

shikjohari