Method summary for loop deletion of elements in java

  • 2020-05-19 04:55:49
  • OfStack

In my mind, the way in which the loop removes elements in list and USES the for loop is problematic, but you can use the enhanced for loop, and then when you use it today, you find that there is an error, and then you go to the popular science for 1 time, and then you find that this is a mistake. Let's talk about 1. Hand out the party can directly jump to the end of the article. Look at the summary.

There are three ways to loop through list in JAVA: for loop, enhanced for loop (also known as foreach loop), and iterator loop.

1. for loops through 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 remove an element, the size of list changes and your index changes, causing you to miss elements as you traverse. For example, when you delete the first element and continue to access the second element according to the index, you actually access the third element because the elements after the deleted relationship have moved forward by 1 bit. Therefore, this approach can be used when deleting a specific element, but is not suitable for looping multiple elements.

2. Enhance the for loop


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

The problem with this approach is that continuing the loop after the element has been deleted will send an error message ConcurrentModificationException, because the element has been changed concurrently while in use, causing an exception to be thrown. However, if you use break to jump out immediately after the deletion, no error will be triggered.

3. 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 iterator's remove method will also report the ConcurrentModificationException error mentioned above if list's remove method is used.

Conclusion:

(1) for the loop deletion of a specific element in list, any one of the three methods can be used, but attention should be paid to the problems analyzed above in the use.

(2) if multiple elements in list are deleted by loop, the iterator iterator mode should be used.


Related articles: