Java list and map traversal delete __java

Source: Internet
Author: User
Tags concurrentmodificationexception
List

There are three ways to iterate through the list in Java, for loops, enhanced for loops (that is, commonly called foreach loops), iterator traversal. For loop traversal list

for (int i=0;i<list.size (); i++) {
    if (list.get (i). Equals ("Del"))
        list.remove (i);
}

The problem with this approach is that when you delete an element, the size of the list changes, and your index changes, which can cause you to omit some elements while traversing. For example, when you delete the 1th element and continue to access the 2nd element based on the index, because the elements behind the deleted relationship move one bit forward, the actual access is the 3rd element. Therefore, this approach can be used when deleting a particular element, but is not appropriate for iterating over multiple elements. Enhance for Loop

for (String x:list) {
    if (x.equals ("del"))
        List.remove (x);
}

The problem with this approach is that the continuation of the loop after deleting the element will report the error message concurrentmodificationexception because the element was used with concurrent modifications, causing the exception to be thrown. But the deletion completes immediately uses the break to jump out, does not trigger the error. iterator Traversal

Iterator<string> it = List.iterator ();
while (It.hasnext ()) {
    String x = It.next ();
    if (X.equals ("del")) {
        it.remove ();
    }
}

This way can be normal loop and delete. Note, however, that using the iterator Remove method will also report the Concurrentmodificationexception error mentioned above if the Remove method of the list is used.

Summarize:

(1) To delete a particular element in a list, you can use any of the three methods, but in use you should pay attention to the problems analyzed above.

(2) To remove multiple elements in a list, you should use the iterator iterator method. Map

It is necessary to delete the corresponding data in a map according to the judgment condition, and naturally think of the remove (Object key) function in map call to delete:

Public map<double, Double> ProcessMAP (map<double, double> list) {
        map<double, double> Map = list;< C2/>iterator<double> iter = Map.keyset (). iterator;
        while (Iter.hasnext ()) {
            Double key = Iter.next ();
            if (Key > 5)
                map.remove (key);
        }
        return map;
}

But when running the program, but not the normal deletion of elements, but prompted the "Java.util.ConcurrentModificationException" error, is very puzzled, in

is to find some data on the map found that the implementation of map is not synchronized. If more than one thread in the program accesses a map at the same time, at least one of the threads modifies the map

, it must remain externally synchronized. And by looking at the iterator principle, iterator is working in a separate thread and has a mutex lock, which means

Iterator is not allowed to be changed by the object of the iteration when it is working, so the object obtained by invoking the iterator operation automatically expires when the map is modified by multithreading.

When iterator was created, a Memory index table (a single linked list) was established, which pointed to the original object, and when the original number of objects changed, the cable

The contents of the introduction table are not synchronized, so when the index pointer moves down, the object being iterated is not found and an error occurs. Map, List, set, etc. are dynamic

, the variable number of objects in the data structure, but iterator is one-way immutable, can only read sequentially, can not reverse the operation of the data structure, when the iterator pointed to the original

When the data changed, iterator lost his way.

Now that you have found the cause of the problem, how to solve it. You can remove an element by calling the iterator remove (Object o) function.

The test code is as follows:

Public map<double, Double> ProcessMAP (map<double, double> list) {
        map<double, double> Map = list;< C1/>iterator<double> iter = Map.keyset (). iterator;
        while (Iter.hasnext ()) {
            Double key = Iter.next ();
            if (Key > 5) {
            //   Map.Remove (key);  
            Java.util.ConcurrentModificationException
                iter.remove ();  OK
            }
        } return
        map;
    

Also, the same problem occurs when you call the put (key, value) function to add elements while traversing the map, so you also need to use the corresponding function of the iterator to add it.

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.