Notes in list remove

Source: Internet
Author: User
Tags concurrentmodificationexception

Import java. util .*;

Public class object {

Public static void main (string [] ARGs ){

String str1 = new string ("ABCDE ");

String str2 = new string ("ABCDE ");

String str3 = new string ("ABCDE ");

String str4 = new string ("ABCDE ");

String str5 = new string ("ABCDE ");

List list = new arraylist ();

List. Add (str1 );

List. Add (str2 );

List. Add (str3 );

List. Add (str4 );

List. Add (str5 );

System. Out. println ("list. Size () =" + list. Size ());

For (INT I = 0; I <list. Size (); I ++ ){

If (string) list. Get (I). startswith ("ABCDE ")){

List. Remove (I );

}

}

System. Out. println ("After remove: List. Size () =" + list. Size ());

}

}

The running result is not:

List. Size () = 5

After remove: List. Size () = 0

Actually:

List. Size () = 5

After remove: List. Size () = 2

Cause: after each element is removed from the list, the subsequent elements move forward. If I = I + 1 is executed, the elements that have just been moved are not read.

Solution:

1. traverse the list.

For (INT I = List. Size ()-1; I> = 0; I --){

If (string) list. Get (I). startswith ("ABCDE ")){

List. Remove (I );

}

}

2. I will be moved back after each element is removed.

For (INT I = 0; I <list. Size (); I ++ ){

If (string) list. Get (I). startswith ("ABCDE ")){

List. Remove (I );

I = I-1;

}

}

3. Delete using iterator. Remove ()

For (iterator it = List. iterator (); it. hasnext ();){

String STR = (string) it. Next ();

If (Str. Equals ("chengang ")){

It. Remove ();

}

}

Note: If you delete a list or set traversal, an error is returned.

Concurrentmodificationexception encountered at work. The Code is as follows:

List list = ...;

For (iterator iter = List. iterator (); ITER. hasnext ();){

Object OBJ = ITER. Next ();

...

If (***){

List. Remove (OBJ );

}

}

After the Remove Method is executed, execute the loop, ITER. when next (), report Java. util. concurrentmodificationexception (of course, if the last one is removed, the next () operation will not be executed again)

Next let's take a look at the source code

Public interface iterator <E> {

Boolean hasnext ();

E next ();

Void remove ();

}

Public Interface collection <E> extends iterable <E> {

...

Iterator <E> iterator ();

Boolean add (e o );

Boolean remove (Object O );

...

}

 

 

There are two remove methods.

Next let's take a look at abstractlist.

Public abstract class implements actlist <E> extends abstractcollection <E> implements list <E> {

// Both abstractcollection and list inherit collection.

Protected transient int modcount = 0;

Private class itr implements iterator <e >{// internal class itr

Int cursor = 0;

Int lastret =-1;

Int expectedmodcount = modcount;

Public Boolean hasnext (){

Return cursor! = Size ();

}

Public E next (){

Checkforcomodification (); // pay special attention to this method.

Try {

E next = get (cursor );

Lastret = cursor ++;

Return next;

} Catch (indexoutofboundsexception e ){

Checkforcomodification ();

Throw new nosuchelementexception ();

}

}

Public void remove (){

If (lastret =-1)

Throw new illegalstateexception ();

Checkforcomodification ();

Try {

Abstractlist. This. Remove (lastret); // execute the remove object operation.

If (lastret <cursor)

Cursor --;

Lastret =-1;

Expectedmodcount = modcount; // reset the value of expectedmodcount to avoid concurrentmodificationexception.

} Catch (indexoutofboundsexception e ){

Throw new concurrentmodificationexception ();

}

}

Final void checkforcomodification (){

If (modcount! = Expectedmodcount) // when expectedmodcount and modcount are not equal, concurrentmodificationexception is thrown.

Throw new concurrentmodificationexception ();

}

}

}

Remove (Object O) is implemented as follows in arraylist:

Public Boolean remove (Object O ){

If (O = NULL ){

For (INT Index = 0; index <size; index ++)

If (elementdata [Index] = NULL ){

Fastremove (INDEX );

Return true;

}

} Else {

For (INT Index = 0; index <size; index ++)

If (O. Equals (elementdata [Index]) {

Fastremove (INDEX );

Return true;

}

}

Return false;

}

Private void fastremove (INT index ){

Modcount ++; // only modcount is added

....

}

Therefore, the cause of concurrentmodificationexception is:

After the remove (Object O) method is executed, modcount and expectedmodcount are not equal. Then, when the code is executed to the next () method, the checkforcomodification () method is judged, and the exception is thrown if two values are not equal.

To avoid this exception, you should use the remove () method.

Here we will not look at the add (Object O) method, which is the same reason, but there is no corresponding add () method. Generally, another list is created.

The following are other explanations on the Internet, which can be explained in essence:

Iterator works in an independent thread and has a mutex lock. After the iterator is created, a single-chain index table pointing to the original object will be created. When the number of original objects changes, the content of the index table will not change simultaneously, therefore, when the index pointer moves backwards, the object to be iterated cannot be found. Therefore, iterator will immediately throw Java according to the fail-fast principle. util. concurrentmodificationexception exception.

Therefore, iterator cannot be changed when it is working. However, you can use the iterator method to remove () to delete objects. The iterator. Remove () method will maintain index consistency while deleting the current iteration object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.