Monday, 15 August 2011

Ambiguity of Remove Method in Java ArrayList -


Generally, the removal process for the application in Java has been shown as the following:

   

ArrayList & LT; String & gt; List = New Arrestist & lt; String & gt; (); List.add ("abc"); List.add ("EFG"); List.remove (1); // ArrayList is removing the second element in the list.remove ("abc"); // Remove the element with the value "abc" in ArrayList

However, there is a situation where overloading is not working.

  ArrayList & lt; Integer & gt; Numbers = New Arreelist & lt; Integer & gt; ();  

numbers.ed (1); Numbers.add (2); When I tried to remove element 2 with value. It gives me an error:

  java.lang.IndexOfBoundsException: Index: 2, Size: 2 on java.util.ArrayList.RangeCheck (ArrayList .Java: 547) java.util.ArrayList Remove (ArrayList.java:387)  

It seems that when it comes to removing this number, I can not remove the element with a specific value. Because the computer will assume all integer values ​​as the index, not the value of the element.

This is a subtle error, what is the other easy way to remove an element with a specific integer value?

You need to use the integer object .

  ArrayList & lt; Integer & gt; Numbers = New Arreelist & lt; Integer & gt; (); Numbers.add (5); Numbers.add (10); Numbers Away (new integer (5)); System.err.println (number); // print [10]  

No comments:

Post a Comment