List delete operation Java.util.ConcurrentModificationException

Source: Internet
Author: User
Tags concurrentmodificationexception

First, let's look at a piece of code:

public static void Main (string[] args) {

list<string> liststr = new arraylist<string> ();
Liststr.add ("1");
Liststr.add ("2");
Liststr.add ("3");
Liststr.add ("4");
Liststr.add ("5");

System.out.println ("Liststr.size:::" +liststr.size ());

for (String str:liststr) {
if ("3". Equals (str)) {
Liststr.remove (str);

}
}


System.out.println ("Liststr.size:::" +liststr.size ());

Phenomenon:

The program throws a Java.util.ConcurrentModificationException exception.

Analysis:

An java.util.ConcurrentModificationException exception is thrown when an attempt is made to modify the contents of a collection/map directly during an iterative operation on Collection or MAP. Because the data in the original list cannot be synchronized while the data is being modified, the data cannot be found in the next loop.

Workaround:

Iterator at work is not allowed to be iterated objects are changed, using the Iterator itself method remove () to delete the
Like, the Iterator.remove () method maintains the consistency of the index while deleting the current iteration object.

Post-Change Code:

public static void Main (string[] args) {

list<string> liststr = new arraylist<string> ();
Liststr.add ("1");
Liststr.add ("2");
Liststr.add ("3");
Liststr.add ("4");
Liststr.add ("5");

System.out.println ("Liststr.size:::" +liststr.size ());

iterator<string> ite = Liststr.iterator ();
while (Ite.hasnext ()) {
String str = (string) ite.next ();
if ("3". Equals (str)) {
Ite.remove ();
}
}


System.out.println ("Liststr.size:::" +liststr.size ());

}

Add:

Perhaps someone might ask, if I don't have to enhance the For loop, can I use the. Get (index) method to make an error?

The code is as follows:

for (int i = 0; i < liststr.size (); i++) {
if ("3". Equals (Liststr.get (i))) {
Liststr.remove (i);
}
}

Phenomenon:

Liststr.size:::5
Liststr.size:::4

You can see that there is no error in modifying the list data through the list's following table index.

Analysis:

You can think of it this way: when the loop is drawn, the JVM records the cited value, and when the current object is removed, the index number of the other element does not change synchronously. The corresponding data can still be found in the next loop. In the case of an enhanced for loop, the current object is recorded, and when the next loop, the object is first found, then the cursor moves down, and the object is not found, so the result is confusing.

Java.util.ConcurrentModificationException

Introduction

Often when iterating over a collection element, you want to modify the collection (Add/remove) operation, similar to the following code:

[Java]View Plaincopy
    1. for (iterator<integer> it = List.iterator (); It.hasnext ();) {
    2. Integer val = It.next ();
    3. if (val = = 5) {
    4. List.remove (Val);
    5. }
    6. }


Running this code throws an exception java.util.ConcurrentModificationException.

Questions

(ArrayList) in ArrayList, its modification operation (add/remove) modcount This field +1,modcount can be regarded as a version number, each time the elements in the collection are modified, will be +1 (even if overflow). Then look at the Iteraor method in Absrtactlist

[Java]View Plaincopy
    1. Public iterator<e> Iterator () {
    2. return new Itr ();
    3. }

It returns an inner class that implements the iterator interface with the following code:

[Java]View Plaincopy
  1. Private class Itr implements iterator<e> {
  2. int cursor = 0;
  3. int lastret =-1;
  4. int expectedmodcount = Modcount;
  5. Public Boolean hasnext () {
  6. return cursor! = size ();
  7. }
  8. Public E Next () {
  9. Checkforcomodification ();
  10. try {
  11. E next = get (cursor);
  12. Lastret = cursor++;
  13. return next;
  14. } catch (Indexoutofboundsexception e) {
  15. Checkforcomodification ();
  16. throw new Nosuchelementexception ();
  17. }
  18. }
  19. public Void Remove () {
  20. if (Lastret = =-1)
  21. throw new IllegalStateException ();
  22. Checkforcomodification ();
  23. try {
  24. Abstractlist.  This.remove (Lastret);
  25. if (Lastret < cursor)
  26. cursor--;
  27. Lastret =-1;
  28. //Modify the value of Expectedmodcount
  29. Expectedmodcount = Modcount;
  30. } catch (Indexoutofboundsexception e) {
  31. throw new Concurrentmodificationexception ();
  32. }
  33. }
  34. final void Checkforcomodification () {
  35. if (modcount! = expectedmodcount)
  36. throw new Concurrentmodificationexception ();
  37. }
  38. }


In the inner class ITR, there is a field expectedmodcount that is initialized equal to Modcount, that is, when we call List.iterator () to return an iterator, the field is initialized to be equal to Modcount. The Next/remove method in class ITR has a call to the Checkforcomodification () method, in which modcount = = Expectedmodcount is detected, If not quite then throw an exception concurrentmodificationexception.

As stated earlier, in the set modification operation (Add/remove), the Modcount was +1.
Take a look at the code that just started, during the iteration, execute List.remove (val), make Modcount+1, Next loop, execute It.next (), checkforcomodification method Find Modcount! = Expectedmodcount, an exception is thrown.

"Solution"
What if you want to perform a delete element operation during an iteration?
Then take a look at the Remove () method of the inner class ITR, after deleting the element, there is a sentence Expectedmodcount = Modcount, which synchronously modifies the value of Expectedmodcount. So, if you need to delete an element while using an iterator iteration, you can use the Remove method provided by the iterator. For an add operation, it is not allowed during the entire iterator iteration. The same is true for other collections (Map/set) using iterator iterations.

    //Awards show     PublicString prizelist () {votelist=Userworksservice.getallrank (); Userworks Userworks=NewUserworks (); Iterator<UserWorks> list =Votelist.iterator ();        Integer rank;  while(List.hasnext ()) {Userworks=List.next (); if(! ("9". Equals (Userworks.getawardsrank ()))) {Rank= Integer.parseint (Userworks.getawardsrank ()) +2; Userworks.setawardsrank (Rank+"");            Alllist.add (Userworks);        }} votelist.removeall (Alllist); return"Prizelist"; }

List delete operation Java.util.ConcurrentModificationException

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.