in project development, we may often need to dynamically delete some elements in the ArrayList.
A wrong way:
[Java]View PlainCopy
- for (int i = 0, len= list.size (); i<len;++i) {
- if (List.get (i) ==xxx) {
- List.remove (i);
- }
- }
The following exception is thrown in this way:
[Java]View PlainCopy
- Exception in thread "main" Java.lang.IndexOutOfBoundsException:Index: 3, Size: 3
- At Java.util.ArrayList.RangeCheck (Unknown Source)
- At Java.util.ArrayList.get (Unknown Source)
- At Listdemo.main (Listdemo.java:)
Because you removed the element, but did not change the subscript of the iteration, so that when the iteration to the last one will throw an exception.
The following improvements can be made to the above program:
[Java]View PlainCopy
- for (int i = 0, len= list.size (); i<len;++i) {
- if (List.get (i) ==xxx) {
- List.remove (i);
- --len; //Reduce a
- I.; //Thank you for Deny_guoshou, if you do not add a comment on the 1 floor of the situation.
- }
- }
The code above is correct.
Let's introduce another scenario:
The iterator interface is implemented inside the list interface, providing a developer with a iterator () to get a iterator object for the current list object.
[Java]View PlainCopy
- iterator<string> slistiterator = List.iterator ();
- while (Slistiterator.hasnext ()) {
- String e = Slistiterator.next ();
- if (E.equals ("3")) {
- Slistiterator.remove ();
- }
- }
The above is also correct, and the second option is recommended.
Both implementations are poorly implemented, and the second is just the JDK package.
View ArrayList source code you will find that many methods are implemented internally based on the iterator interface, so the second scenario is recommended.
Java Collection Class ArrayList delete specific elements in a loop