current position:Home>Method summary of circular deletion of elements in list in Java

Method summary of circular deletion of elements in list in Java

2021-08-25 08:45:03 wx611f65369a431

 JAVA Loop delete in list Summary of the methods of the elements in

   Circular deletion in impression list The elements in use for There's a problem with the way the cycle works , But you can use enhanced for loop , Then I found an error when I used it today , Then I went to popularize science , Then I found that this is a misunderstanding . Let's talk about .

  JAVA Middle loop traversal list There are three ways for loop 、 enhance for loop ( That's what they say foreach loop )、iterator Traverse .

 

1、for Loop traversal list

for(int i=0;i<list.size();i++){
    if(list.get(i).equals("del"))
        list.remove(i);
}
      
  • 1.
  • 2.
  • 3.
  • 4.

    The problem with this approach is , After deleting an element ,list There's been a change in the size of , And your index is changing , So it will cause you to miss some elements when traversing . For example, when you delete the second 1 After elements , Continue to access page... According to the index 2 Element time , Because of the deleted relationship, the following elements move forward by one , So the actual visit is no 3 Elements . therefore , This method can be used when deleting a specific element , However, it is not suitable for circular deletion of multiple elements .

 

2、 enhance for loop

for(String x:list){
    if(x.equals("del"))
        list.remove(x);
}
      
  • 1.
  • 2.
  • 3.
  • 4.

    The problem with this approach is , If you continue to cycle after deleting an element, you will report an error message ConcurrentModificationException, Because the element is modified concurrently when it is used , Causes an exception to be thrown . But use it immediately after deletion break Jump out of , An error message will not be triggered .

 

3、iterator Traverse

Iterator<String> it = list.iterator();
while(it.hasNext()){
    String x = it.next();
    if(x.equals("del")){
        it.remove();
    }
}

      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

   This method can cycle and delete normally . But here's the thing , Use iterator Of remove Method , If you use list Of remove The method will also report the above mentioned ConcurrentModificationException error .

 

   summary :

  (1) Loop delete list Of a particular element in a , You can use any of three ways , But in use, we should pay attention to the problems analyzed above .

  (2) Loop delete list Of more than one element , Iterators should be used iterator The way .

copyright notice
author[wx611f65369a431],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825084500069y.html

Random recommended