It is necessary to use an iterator to traverse and delete JAVA sets.

Source: Internet
Author: User

Today, my colleague wrote several lines of code similar to this:

public static void main(String args[]) {    List<String> famous = new ArrayList<String>();    famous.add("liudehua");    famous.add("madehua");    famous.add("liushishi");    famous.add("tangwei");    for (String s : famous) {        if (s.equals("madehua")) {            famous.remove(s);        }    }}

Running exception:

Exception in thread "main" java. util. ConcurrentModificationException

At java. util. effecactlist $ Itr. checkForComodification (effecactlist. java: 372)

At java. util. AbstractList $ Itr. next (AbstractList. java: 343)

At com. bes. Test. main (Test. java: 15)

Java is the easiest way to make mistakes. It is necessary to use an iterator to traverse and delete JAVA collections. Remember.

In fact, for the above for loop, the following code is still converted during the running process:

for(Iterator<String> it = famous.iterator();it.hasNext();){         String s = it.next();         if(s.equals("madehua")){             famous.remove(s);         }     }

The iterator is still used, but the delete operation uses the wrong method. For example, change famous. remove (s) to it. remove ()

And the result is correct.

Of course, if changed:

for (int i = 0; i < famous.size(); i++) {            String s = famous.get(i);            if (s.equals("madehua")) {                famous.remove(s);            }        }

This method can also complete the function, but it is generally not written in this way.

Why can't I use the famous. remove (s) operation when I use the code generator? This is because the mixed use of ArrayList and Iterator will lead to different States, and eventually an exception occurs.

Let's take a look at the implementation of Iterator in ArrayList:

private class Itr implements Iterator<E> {   /**    * Index of element to be returned by subsequent call to next.    */   int cursor = 0;   /**    * Index of element returned by most recent call to next or    * previous.  Reset to -1 if this element is deleted by a call    * to remove.    */   int lastRet = -1;   /**    * The modCount value that the iterator believes that the backing    * List should have.  If this expectation is violated, the iterator    * has detected concurrent modification.    */   int expectedModCount = modCount;   public boolean hasNext() {           return cursor != size();   }   public E next() {           checkForComodification();       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);       if (lastRet < cursor)           cursor--;       lastRet = -1;       expectedModCount = modCount;       } catch (IndexOutOfBoundsException e) {       throw new ConcurrentModificationException();       }   }   final void checkForComodification() {       if (modCount != expectedModCount)       throw new ConcurrentModificationException();   }   }

Basically, ArrayList uses the size attribute to maintain its own State, while Iterator uses cursor to maintain its own State.

When the size changes, the cursor may not be synchronized unless this change is caused by the Iterator.

From the code above, we can see that when the Iterator. remove Method changes the ArrayList list, it will update the cursor to synchronize this change. However, Iterator cannot perceive the ArrayList changes caused by other methods. ArrayList naturally does not take the initiative to inform the Iterator, it will be a heavy job. Iterator tries its best to prevent unexpected consequences caused by inconsistent states. Iterator often performs checkForComodification checks to prevent changes. If there is a change, an exception is thrown, so the above exception occurs.


This article from the "World without thieves" blog, please be sure to keep this source http://guojuanjun.blog.51cto.com/277646/1348450

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.