in Java in the operation of the list is very frequent, especially for the list start traversal, these operations we will, but also very familiar with, but the Java list to delete elements, remove list elements are not familiar with it, can say very strange, is also very easy to make mistakes in the actual operation, first look at the following Java in how to remove the list element bar. Public classTest { Public Static voidMain (string[] args) {String str1=NewString ("ABCDE"); String str2=NewString ("ABCDE"); String STR3=NewString ("ABCDE"); String STR4=NewString ("ABCDE"); String STR5=NewString ("ABCDE"); List List=NewArrayList (); List.add (str1); List.add (str2); List.add (STR3); List.add (STR4); List.add (STR5); System.out.println ("List.size () =" +list.size ()); for(inti = 0; I < list.size (); i++) {if((String) list.get (i)). StartsWith ("ABCDE") {list.remove (i);}} System.out.println ("After remove:list.size () =" +list.size ());}} What do you think the result of this program is printed out? Java code run result is not: list.size ()=5After remove:list.size ()=0instead: Java code list.size ()=5After remove:list.size ()=2What's going on here? How do you want to remove the elements from the list? Cause: After each remove element of the list, the subsequent elements move forward, and if you execute the i=i+1, the element that was just moved is not read. How to solve? There are three ways to solve this problem:1. Traverse the Listjava code backwards for(inti = List.size ()-1; i > = 0; i--) {if((String) list.get (i)). StartsWith ("ABCDE") {list.remove (i); }}2. Remove an element and then move I back to Java code for(inti = 0; I < list.size (); i++) {if((String) list.get (i)). StartsWith ("ABCDE") {list.remove (i); I=i-1; }}3. Use the Iterator.remove () method to remove Java code for(Iterator it =list.iterator (); It.hasnext ();) {String str=(String) it.next (); if(Str.equals ("Chengang") ) {it.remove (); }}
Java-list-remove () Usage analysis of the problem of solving the incorrect data of the Java List remove ()