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?
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]
Try remove(new Integer(1)
. This will work as it ll be a exact match to remove(Object o)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With