How to delete the elements in the list in the time series

Source: Internet
Author: User
Tags concurrentmodificationexception

From: http://uin57.iteye.com/blog/903966

Today, when I was writing code, my head suddenly got short-circuited. I don't know how to delete the elements in the list during traversal.

The following code is generated ..

Code 1: foreach

Package testcollection. testlist; import Java. util. arraylist; public class testremovelist {public static void main (string [] ARGs) {arraylist <testobject> testlist = new arraylist (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (null); For (testobject to: testlist) {If (null = to) {testlist. remove (to); // This line changes the set content }}} class testobject {}

Running result:

Exception in thread "main" java.util.ConcurrentModificationExceptionat java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)at java.util.ArrayList$Itr.next(ArrayList.java:791)at testCollection.testList.TestRemoveList.main(TestRemoveList.java:13)

Analyze the cause:

The List class has the following variables:

protected transient int modCount = 0;

This variable is used to record whether the list is changed (arraylist only)

For example, the add method:

    public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }

Continue to view the ensurecapacityinternal method:

    private void ensureCapacityInternal(int minCapacity) {        modCount++;        // overflow-conscious code        if (minCapacity - elementData.length > 0)            grow(minCapacity);    }

You see, modcount ++.

For example, if the remove method is used, this method will call the fastremove method. This method actually changes the content in the list:

    private void fastRemove(int index) {        modCount++;        int numMoved = size - index - 1;        if (numMoved > 0)            System.arraycopy(elementData, index+1, elementData, index,                             numMoved);        elementData[--size] = null; // Let gc do its work    }

See modcount ++.

The foreach method calls the iterator implementation class returned by iterator:

    public Iterator<E> iterator() {        return new Itr();    }

When you call this method, an itr object is created.

The expectedmodcount variable is initialized during creation. The value of this variable is equal to modcount in the list external class.

int expectedModCount = modCount;

If you do not use the iterator method to list the edge, the modcount value in the list is changed, but the expectedmodcount value here does not change.

So when the next method of the itr object is called:

        public E next() {            checkForComodification();            int i = cursor;            if (i >= size)                throw new NoSuchElementException();            Object[] elementData = ArrayList.this.elementData;            if (i >= elementData.length)                throw new ConcurrentModificationException();            cursor = i + 1;            return (E) elementData[lastRet = i];        }

        final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }

Then there will be tragedy.

Thus: Java. util. concurrentmodificationexception.

The original words in JDK 6 are as follows:

The jdk6 API writes public class concurrentmodificationexceptionextends runtimeexception. This exception is thrown when the method detects concurrent object modifications but does not allow such modifications.
For example, when a thread iterates over a collection, it usually does not allow another thread to linearly modify the collection. In these cases, the iteration results are usually uncertain. If this behavior is detected, some iterator implementations (including all common collection implementations provided by JRE) may choose to throw this exception. The iterator that executes this operation is called the fast failure iterator, because the iterator quickly fails completely without the risk of any uncertain behavior at a certain time in the future.
Note that this exception does not always indicate that the object has been modified concurrently by different threads. If a single thread sends a method call sequence that violates the object protocol, the object may throw this exception. For example, if the thread uses the quick failure iterator to directly modify the collection when it iterates on the collection, the iterator will throw this exception.
Note: The Fast failure behavior of the iterator cannot be guaranteed, because in general, it is impossible to make any hard guarantee for non-synchronous concurrent modifications. The quick failed operation will throw concurrentmodificationexception as much as possible. Therefore, writing a program dependent on this exception to improve the correctness of such operations is an incorrect practice. The correct practice is: concurrentmodificationexception should only be used to detect bugs.

In Java, for each actually uses iterator for processing. Iterator does not allow the collection to be deleted during use of iterator. While for each, an element is deleted from the set, which causes iterator to throwConcurrentmodificationexception.

 

Code 2: Get (I)

 

Package testcollection. testlist; import Java. util. arraylist; public class testremovelist2 {public static void main (string [] ARGs) {arraylist <testobject> testlist = new arraylist (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (null); testlist. add (null); For (INT I = 0; I <testlist. size (); I ++) {testobject to = testlist. get (I); If (null = to) {system. out. println ("before removal:" + testlist. size (); testlist. remove (I); // This line changes the set content/** when traversing to the fifth element, I = 4, the length of testlist is sadly changed to 5 (Originally 6) * after this loop is executed, I ++ is changed to 5, and 5 is not less than 5, so there is no loop, the last null element is not removed */system. out. println ("when an element is removed:" + testlist. size () + "" + I) ;}}for (testobject to: testlist) {system. out. println ();}}}

Running result:

Before removing: 6 when removing an element: 5 4testCollection.testList.TestObject@a0002dftestCollection.testList.TestObject @ 6bc839atestCollection.testList.TestObject@4263f6eatestCollection.testList.TestObject @ 30e79eb3null

Alternative method:

Package testcollection. testlist; import Java. util. arraylist; public class testremovelist3 {public static void main (string [] ARGs) {arraylist <testobject> testlist = new arraylist (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (New testobject (); testlist. add (null); testlist. add (null); int length = testlist. size (); For (INT I = 0; I <length; I ++) {// This will cross-border testobject to = testlist. get (I); If (null = to) {testlist. remove (I) ;}for (testobject to: testlist) {system. out. println ();}}}

Running result:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5at java.util.ArrayList.rangeCheck(ArrayList.java:604)at java.util.ArrayList.get(ArrayList.java:382)at testCollection.testList.TestRemoveList3.main(TestRemoveList3.java:16) 

The result is that the filtered data is incomplete. When two consecutive elements are null, there will be a fish that falls into the net.

The reason is: When an element is deleted from a set, the size of the set will decrease and the associated indexes will change!

Code 3: iterator

 

package testCollection.testList;import java.util.ArrayList;import java.util.Iterator;public class TestRemoveList4 {public static void main(String[] args) {ArrayList<TestObject> testList = new ArrayList();testList.add(new TestObject());testList.add(new TestObject());testList.add(new TestObject());testList.add(new TestObject());testList.add(null);testList.add(null);for (Iterator<TestObject> it = testList.iterator();it.hasNext();){              TestObject to=it.next();              if(to==null ){                  it.remove();                                }          }  for(TestObject to : testList){System.out.println(to);}}}

Running result:

testCollection.testList.TestObject@3c0f3387testCollection.testList.TestObject@a0002dftestCollection.testList.TestObject@6bc839atestCollection.testList.TestObject@4263f6ea

This time is correct

In the JDK manual, the remove () method in iterator is described as remove.
void remove()
Removes the last element returned by the iterator from the set to which the iterator points (optional ). Each call NextThis method can be called only once. If the set pointed to by the iterator is modified in other ways than this method, the iterator behavior is unclear.

 

Throw:
UnsupportedOperationException-If the iterator is not supported RemoveOperation.
IllegalStateException-If you have not called NextMethod, or the last call NextThe method has been called. RemoveMethod.

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.