Today, we will traverse an arraylist to check whether an item exists. If so, we will delete it from the list as follows:
- For(Person P: Persons ){
- If(P. getname (). Equals (name ))
- Persons. Remove (P );
- }
For (person P: Persons) {If (P. getname (). Equals (name) Persons. Remove (p );}
Java. util. concurrentmodificationexception: A concurrency error. I Googled the Internet and explained that if the current element is deleted while traversing the arraylist, Java is triggered. util. concurrentmodificationexception: "To ensure the smooth completion of the traversal process, you must ensure that the content of the set is not changed during the traversal process (except for the remove () method of iterator). Therefore, the principle to ensure reliable traversal is to use this set only in one thread, or to traverseCode."
Solution 1:
- // Use Java. util. iterator
- For(Iterator it = List. iterator (); it. hasnext ();){
- Integer I = (integer) it. Next ();
- It. Remove ();
- }
// Use Java. util. iterator for (iterator it = List. iterator (); it. hasnext ();) {INTEGER I = (integer) it. next (); it. remove ();}
Solution 2:
- For(IntI =0; I <persons. Size (); I ++ ){
- If(Persons. Get (I). getname (). Equals (name ))
- Persons. Remove (I );
- }
For (INT I = 0; I <persons. size (); I ++) {If (persons. get (I ). getname (). equals (name) persons. remove (I );}
Method 2 is not suitable for large arrays