Deletes the implementation code for the elements in the JAVA collection

  • 2020-04-01 02:04:11
  • OfStack

Often we want to delete some elements from the collection. Some might write it like this.


  public void operate(List list){
  for (Iterator it = list.iterator(); it.hasNext();) {
  String str = (String)it.next();
  if (str.equals("chengang")){
  list.remove(str);
  }
  }
  }

This method will report the following exception as soon as it runs:

The Exception in the thread "main" Java. Util. ConcurrentModificationException
The at Java. Util. AbstractList $Itr. CheckForComodification (449), AbstractList. Java:

Because a list cannot delete its elements while in a loop. Then I did it this way, a stupid way, the idea is this: create a List for the elements to be deleted, after a loop, use the list.removeall method to remove the elements. The code is as follows:


  public void operate(List list){
  List removeList= new ArrayList();
  for (Iterator it = list.iterator(); it.hasNext();) {
  String str = (String)it.next();
  if (str.equals("chengang")){
  removeList.add(str);
  }
  }
  list.removeAll(removeList);
  }

This does solve the problem, but the method is too cumbersome. There is a simpler and more efficient way to do it, which is to use the iterator.remove method, as follows:


  for (Iterator it = list.iterator(); it.hasNext();) {
  String str = (String)it.next();
  if (str.equals("chengang")){
  it.remove();
  }
  }

So, the more you know about the basics of Java, the cleaner your code will be. On the other hand, if your code is particularly complex, there is something wrong with the method or design.


Related articles: