A remove data trap in the Java collection (iterates through the collection itself and simultaneously deletes the traversed data)

Source: Internet
Author: User
Tags set set concurrentmodificationexception

Here are some other explanations on the web that can explain the reasons in essence:
Iterator is working in a separate thread, and has a mutex lock. Iterator is created after the creation of a single-chain index table pointing to the original object, when the original object number changes, the contents of the index table will not be synchronized changes, so when the index pointer moves back to find the object to iterate, so according to Fail-fast principle Iterator The java.util.ConcurrentModificationException exception is thrown immediately.
So Iterator is not allowed to be changed by iterative objects while working. But you can delete the object using Iterator's own method, remove (), and the Iterator.remove () method maintains the consistency of the index while deleting the current iteration object.

The common collection framework in Java is List, set, and map.

The list can be traversed by subscript, and Set,map cannot be traversed by the following table, so the iterator is often used for set, map data traversal, but there is a trap when using iterators to remove data.

Execute the following code:

Set set = new HashSet ();

Set.add (1);

Set.add (2);

Set.add (3);

Iterator i = Set.iterator ();

while (I.hashnext ()) {

Object o = I.next ();

Set.remove (o);

}

The following exception occurs when you execute the result:

Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.abstractlist$itr.checkforcomodification (Unknown Source)
At Java.util.abstractlist$itr.next (Unknown Source)

This problem exists when the collection framework iterates through the data using iterators, and also in Java5 's new foreach traversal mode. There is no problem with traversing the list through the following table.

Such as:

List List = new ArrayList ();

List. Add (1);

List.add (2);

List.add (3);

for (int i = 0; i < list.size (); i++) {

List.remove (List.get (i)); | | List.remove (i);

}

//

Or use the iterator Remove method

The code can execute normally.

Of course, this is also easy to solve, the implementation of the way is to talk about traversal and removal operation separation, that is, in the process of traversal, will need to remove the data stored in another set, after the end of the traversal, the unified removal.

------------------------------------------------------------------------------------------------------

Use Java iterator itetator to traverse and delete element problems in HashMap

Problem:
The following code attempts to traverse the HashMap with the HashMap iterator object and delete the element that satisfies the condition (such as the timeout element), but throws a Java.util.ConcurrentModificationException exception
public static void Main (string[] args)
{
Hashmap<string, string> hs=new HashMap ();
Hs.put ("P1", "1");
Hs.put ("P2", "1");
Hs.put ("P3", "1");
Hs.put ("P4", "1");
Hs.put ("P5", "1");
Hs.put ("P6", "1");
Iterator It=hs.keyset (). Iterator ();
while (It.hasnext ())
{
String str= (String) it.next ();
SYSTEM.OUT.PRINTLN (HS);

Logic processing .....
.............
Hs.remove (str);
}
}
The reason should be Hs.remove (str), the IT content remains the same, and the pointer list in it is reordered, so as long as you ensure that any element is removed, it stays in sync:
Solution One: After you remove any element, it keeps synchronizing updates
............
Iterator It=hs.keyset (). Iterator ();
while (It.hasnext ())
{
It=hs.keyset (). iterator ();
String str= (String) it.next ();
SYSTEM.OUT.PRINTLN (HS);

Logic processing .....
.............
Hs.remove (str);
}
...........
This time complexity is obviously too large (two-layer loop nesting)
Solution Two:
Because the iterator objects of HS are reordered when the elements are deleted, only one copy of the HS is used Hsback
Uackp iterator to traverse the HS so that iterator does not reflow when the HS element is removed (because the element of HS is removed, not the HSBACKUACKP that the iterator belongs to)
...................
Hsbackup= (hashmap<string, string>) Hs.clone ();
Iterator It=hsbackup.keyset (). Iterator ();
System.out.println (Hsbackup);
while (It.hasnext ())
{
String str= (String) it.next ();
SYSTEM.OUT.PRINTLN (HS);
Hs.remove (str);
}
.....................
In this way, although the complexity of the time is small (only a layer of circulation), but the space complexity is large (more than a hashmap copy);
After reviewing the API documentation and related materials, the original iterator object has a Remove method:
void Remove ()
Removes from the underlying collection, the last element, returned by the
Iterator (optional operation). This method can is called only once per
Call to next. The behavior of an iterator is unspecified if
The underlying collection is modified while the iteration are in
Progress in any-than by calling this method.
So there are the following improvements:
Solution Three:
..............................
Iterator It=hs.keyset (). Iterator ();
while (It.hasnext ())
{
String str= (String) it.next ();
SYSTEM.OUT.PRINTLN (HS);
It.remove ();
}
..............................

A remove data trap in the Java collection (iterates through the collection itself and simultaneously deletes the traversed data)

Related Article

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.