import java.util.*;

public class object {

public static void main(String[] args) {

String str1 = new String("abcde");

String str2 = new String("abcde");

String str3 = new String("abcde");

String str4 = new String("abcde");

String str5 = new String("abcde");

List list = new ArrayList();

list.add(str1);

list.add(str2);

list.add(str3);

list.add(str4);

list.add(str5);

System.out.println("list.size()=" + list.size());

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

if (((String) list.get(i)).startsWith("abcde")) {

list.remove(i);

}

}

System.out.println("after remove:list.size()=" + list.size());

}

}

The running result is not :

list.size()=5

after remove:list.size()=0

was :

list.size()=5

after remove:list.size()=2

reason :List Every time remove After dropping an element , The elements behind will move forward , At this point, if you execute i=i+1, The element just moved is not read .

    One at a time , The following element moves to the previous one , So lead to i+1 The element of position is not deleted .

resolvent :

1. The other way round list

for (int i = list.size()-1; i > =0; i--) {

if (((String) list.get(i)).startsWith("abcde")) {

list.remove(i);

}

}

2. Every time you remove an element, you put i Move back

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

if (((String) list.get(i)).startsWith("abcde")) {

list.remove(i);

i=i-1;

}

}

3. Use iterator.remove() Methods to remove

for (Iterator it = list.iterator(); it.hasNext();) {

String str = (String)it.next();

if (str.equals("chengang")){

it.remove();

}

}

Be careful : In a traverse list Or in the process of traversing the collection , If you delete it, you will report an error

I met a guy at work ConcurrentModificationException. The code is as follows :

List list = ...;

for(Iterator iter = list.iterator(); iter.hasNext();) {

Object obj = iter.next();

...

if(***) {

list.remove(obj);

}

}

In execution remove After method , Then execute the loop ,iter.next() When , newspaper java.util.ConcurrentModificationException( Of course , If remove The last one is , It's not going to be executed again next() Operation )

Let's take a look at the source code

public interface Iterator<E> {

boolean hasNext();

E next();

void remove();

}

public interface Collection<E> extends Iterable<E> {

...

Iterator<E> iterator();

boolean add(E o);

boolean remove(Object o);

...

}

There are two remove Method

Let's take a look at AbstractList

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

//AbstractCollection and List All inherited Collection

protected transient int modCount = 0;

private class Itr implements Iterator<E> { // Inner class Itr

int cursor = 0;

int lastRet = -1;

int expectedModCount = modCount;

public boolean hasNext() {

return cursor != size();

}

public E next() {

checkForComodification(); // Pay special attention to this method

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); // perform remove Operations on objects

if (lastRet < cursor)

cursor--;

lastRet = -1;

expectedModCount = modCount; // Reset expectedModCount Value , Avoided ConcurrentModificationException The birth of

} catch(IndexOutOfBoundsException e) {

throw new ConcurrentModificationException();

}

}

final void checkForComodification() {

if (modCount != expectedModCount) // When expectedModCount and modCount When they are not equal , Throw out ConcurrentModificationException

throw new ConcurrentModificationException();

}

}

}

remove(Object o) stay ArrayList The implementation is as follows :

public boolean remove(Object o) {

if (o == null) {

for (int index = 0; index < size; index++)

if (elementData[index] == null) {

fastRemove(index);

return true;

}

} else {

for (int index = 0; index < size; index++)

if (o.equals(elementData[index])) {

fastRemove(index);

return true;

}

}

return false;

}

private void fastRemove(int index) {

modCount++; // Only added modCount

....

}

therefore , produce ConcurrentModificationException The reason is :

perform remove(Object o) After method ,modCount and expectedModCount It's not equal . And then when the code goes to next() When the method is used , Determine the checkForComodification(), It's found that the two values are not equal , It's time to throw out the Exception.

To avoid this Exception, You should use remove() Method .

Here we don't look at add(Object o) The method , It's the same reason , But there is no corresponding add() Method . In general , Just build another one List 了

Here are other explanations on the Internet , It's better to explain why in essence :

Iterator It's working in a separate thread , And have a mutex lock . Iterator After being created, a single chain index table pointing to the original object will be created , When the original number of objects changes , The contents of this index table will not be changed synchronously , So when the index pointer moves back, it can't find the object to be iterated , So, in accordance with the fail-fast principle Iterator It'll be thrown right away java.util.ConcurrentModificationException abnormal .

therefore Iterator Objects that are iterated are not allowed to be changed while working . But you can use Iterator In its own way remove() To delete objects , Iterator.remove() Method maintains index consistency while deleting the current iteration object .

List aggregate remove More articles on the problem of elements

  1. Not in foreach It's going on in the cycle remove/add operation .remove Element please use Iterator The way , If concurrent operations , Need to be right Iterator Object locking

    Not in foreach It's going on in the cycle remove/add operation .remove Element please use Iterator The way , If concurrent operations , Need to be right Iterator Object locking . Example : Iterator&l ...

  2. Traverse List An error is reported when deleting elements in the collection

    Traverse List An error is reported when deleting elements in the collection   Traverse List When deleting elements in a collection, there will be problems such as index out of bounds exception or incomplete traversal of content . Example : List<String> al = new ArrayList< ...

  3. List Sort the elements in a collection

    Application scenarios : In the course of development, we often encounter the problem of List<Object> Set to sort , And sort according to an attribute of the objects in the collection     -------- Here's the solution public static ...

  4. js Traversing the collection, deleting elements

    js Traversing the collection, deleting elements /** * Effective way - Change the subscript , Control traversal */ for (var i = 0; i < arr.length; i++) { if (...) { arr.spli ...

  5. About HashSet aggregate add Elements

    HashSet aggregate add The underlying implementation of the element uses HashMap. Simple memory : No matter what HashMap put Element or HashSet add Elements , Call... First hashCode() Method , if hashCode Method return value is different ...

  6. hdu 1856 Find the number of elements in the set What is the maximum number of outputs

    Find the number of elements in the set What is the maximum number of outputs Sample Input41 23 45 61 641 23 45 67 8 Sample Output42 # include <iostream&g ...

  7. poj 1611 seek 0 The number of elements in the set of node No

    seek 0 The number of elements in the set of node No Sample Input 100 42 1 25 10 13 11 12 142 0 12 99 2200 21 55 1 2 3 4 51 00 0Sample Out ...

  8. List in remove Understanding of elements

    Today I wrote a simple list in remove Element method , The result is wrong ... List<String> ll = Arrays.asList("1","2",& ...

  9. C# Do not allow the foreach Changing the values of elements in an array or collection in a loop ( notes : The value of the member is not affected )

    C# Do not allow the foreach Changing the values of elements in an array or collection in a loop ( notes : The value of the member is not affected ), If the following code will not compile . foreach (int x in myArray) { x++; // Error code , Because of change ...

Random recommendation

  1. sublime3 Add pair react Code checking

    install eslint npm install -g eslint npm install -g eslint-plugin-react After installation, call eslint --init initialization , Generate .eslintr ...

  2. g++ Compilation options

    -g, Generate executable files for debugging , Can be in gdb Run in . Because the file contains debugging information, the running efficiency is very low , And the files are quite large . -c: The generated name is source_file.o The target file of . -o, Specify output file name , Can cooperate with ...

  3. css Central solutions

    Horizontal center An element within a row or having the properties of an element within a row ( Like text or links )? Center a row element whose parent is a block level element horizontally , Sure :CSS: 1 2 3 .center-children { text-align: ce ...

  4. use WinDbg debugging Windows And drivers

    Due to my limited ability , Please understand the shortcomings of translation , Welcome criticism and correction :sunylat@163.com MSDN original text :https://msdn.microsoft.com/zh-cn/library/windows/h ...

  5. VirtualBox Middle virtual Ubuntu Add a new virtual hard disk

    VirtualBox Install it in the middle Ubuntu after , Found that hard disk space is not enough 了 . Here's the solution to this : 1. Add a new hard disk Set up -> Storage -> SATA controller -> Right click , choice &qu ...

  6. use Canvas Make a little game —— snake

    What about today , I'd like to share with my friends the process from conception to realization of a snake game ~ Because I don't really like direct PO Code , So only copy Code children's shoes, please go out and turn left. Thank you . Logically speaking canvas Its application is a platitude , But I couldn't search in the preparation stage ...

  7. linux and windows Synchronous data cwrsync client to rsync server

    linux and windows Synchronous data ,rsync server  cwrsync client linux server Most systems come with rsync, If not, mount the system disk and install it yourself , The installation is very simple. I don't need to do more ...

  8. adopt VBA, When in EXCEL Enter any date format in the cell , Can be automatically converted to the specified standard format of the date value

    In daily input EXCEL In the cells of the table , Let's enter some general date content , Such as :2017-10-17 or 2017/10/17 when ,EXCEL It is automatically recognized as a date and displayed in a cell design format , The values stored in cells are also in date format ...

  9. JavaScript Array of 22 Methods

    original text :http://www.cnblogs.com/xiaohuochai/p/5682621.html javascript Array of 22 Methods   In front of the word The array has a total of 22 Methods , In this paper, it is divided into two parts ...

  10. MySQL Master slave synchronization problems and solutions

    When working on a project , Using the master-slave database ,master be responsible for update.delete.insert operation , and slave be responsible for select operation . scene 1: Publish articles and view articles Think of this project as a blogging system , This is it ...