First, the incorrect opening method:
First: Use the For loop to delete the elements of the collection, as shown in the sample code
1 New Arraylist<string> (Arrays.aslist ("A", "B", "C", "D")); 2 for (int i = 0; i < list.size (); i++) {3 list.remove (i); 4 }5 System.out.println (list);
The result output is:
[B, D]
Explanation begins:
First look at the source:
1 PublicE Remove (intindex) {2 Rangecheck (index);3modcount++;4E OldValue =Elementdata (index);5 intnummoved = size-index-1;6 if(nummoved > 0)7System.arraycopy (Elementdata, index+1, Elementdata, index,8 nummoved);9Elementdata[--size] =NULL;//clear to let GC do it workTen returnOldValue; One}
Explanation: For the first time into a for loop, i=0, call the Remove method to remove the first element, the collection size contraction, the first time the deletion is complete, the list becomes "B,c,d"; Loop again, I=1, call the Remove method to delete the C collection size again, the list becomes "B,d" Cycle, i=2, non-conforming, end of cycle
Second: Delete the element using the Foreach loop, the sample code is as follows
1 New Arraylist<string> (Arrays.aslist ("A", "B", "C", "D")); 2 for (String s:list) {3 if (S.equals ("B")) 4 List.remove (s); 5 }6 System.out.println (list);
The result: The code unexpectedly throws an exception java.util.ConcurrentModificationException.
Explanation begins:
First look at the source code:
1 PublicIterator<e>iterator () {2 return NewItr ();3 }4 /**5 * An optimized version of Abstractlist.itr6 */7 Private classItrImplementsIterator<e> {8 intCursor//index of next element to return9 intLastret =-1;//index of last element returned;-1 if no suchTen intExpectedmodcount =Modcount; One Public BooleanHasnext () { A returnCursor! =size; - } -@SuppressWarnings ("Unchecked") the PublicE Next () { - checkforcomodification (); - inti =cursor; - if(I >=size) + Throw Newnosuchelementexception (); -object[] Elementdata = ArrayList. This. Elementdata; + if(I >=elementdata.length) A Throw Newconcurrentmodificationexception (); atcursor = i + 1; - return(E) Elementdata[lastret =i]; - } - Public voidRemove () { - if(Lastret < 0) - Throw Newillegalstateexception (); in checkforcomodification (); - Try { toArrayList. This. Remove (Lastret); +cursor =Lastret; -Lastret =-1; theExpectedmodcount =Modcount; *}Catch(Indexoutofboundsexception ex) { $ Throw Newconcurrentmodificationexception ();Panax Notoginseng } - } the Final voidcheckforcomodification () { + if(Modcount! =expectedmodcount) A Throw Newconcurrentmodificationexception (); the } +}
Explanation: The foreach Loop in Java works like a iterator.
The first time you enter the Foreach Loop, ArrayList creates an internal iterator class object that is no longer created in the loop. The process for Each loop is to call the Hasnext () method of the Iterator object first, return True, and then call the next () method, and each time the next () method is called, the collection modification is detected first. An instance field of an iterator object is the key to detection. Instance fields are assigned one time when the object is created, and no maintenance is followed. when the Remove (Object obj) method is called, the collection itself tracks the overwrite operation (add or delete), and the Arraylis class object maintains a rewritten variable that is independent of the count value maintained by the iterator object. internal iterator Class object next () method first, determine whether the set's overwrite variable equals the iterator's overwrite value, not equal to throw an exception. PS:It was found in the test that if remove is the second-to-last element of the collection or the final element, no exception will be thrown. Because after remove, the iterator points to the end of the collection, and then into the loop, the Hasnext () method returns FALSE. The loop ends.
So, next the right way to open it--
method One: With the traditional for loop, from the last element of the collection forward loop delete elements, the size of the collection will be smaller, and the index will change, but will not affect the previous non-circular elements. The sample code is as follows
1Arraylist<integer> a=NewArraylist<integer> (15);2A.add (222);3A.add (3);4A.add (333);5A.add (000);6A.add (333);7A.add (4);8 9 for(intS=a.size () -1;s>=0;s--){Ten if(A.get (s). Intvalue () ==333){ One A.remove (s); A } -}
method Two: Use the iterator Remove () method to delete the elements
in the collection sample code as follows
1Privatevoid screenblacknamelist (list<sharedboardsmswrapper> source, list<blacknamelistmodel>blacknamelist) { 2Iterator<sharedboardsmswrapper> sourceit=Source.iterator (); 3 while(Sourceit.hasnext ()) {4Sharedboardsmswrapper tmpsharedboardsmswrapper=Sourceit.next (); 5Iterator<blacknamelistmodel> blacknamelistit=Blacknamelist.iterator (); 6 while(Blacknamelistit.hasnext ()) {7Blacknamelistmodel tmpblacknamelistmodel=Blacknamelistit.next (); 8 if(Tmpsharedboardsmswrapper.getsource (). Equals (Tmpblacknamelistmodel.getsource ())) {9 Sourceit.remove (); Ten Break; One } A } - } -}
Java loop removes the correct opening of multiple elements of a collection