Three methods of deleting Java list by traversal

This article mainly introduces three methods of Java list deletion by traversal. The example code is introduced in great detail, which has a certain reference value for everyone's study or work. Friends in need can refer to it

How to easily delete a list through three types of Java traversal:

1. For loop:

Common writing methods for the fifth day of junior high school: (the desired effect cannot be achieved due to subscript problems)

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

It should be changed to: (reverse order operation to avoid subscript problem)

int size = list.size();
for(int i=size-1;i>=0;i--){
  if(list.get(i).equals("del"))
    list.remove(i);
}

2. Enhanced for loop (foreach loop):

Common error: (concurrent modificationexception will be thrown)

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

Should read:

//cowlist为原list
CopyOnWriteArrayList<Record> list = new CopyOnWriteArrayList<Record>(cowList);
for(String x:list){
  if(x.equals("del"))
    list.remove(x);
}

3. Iterator traversal: (note that if the remove method of iterator is used, the remove method of list cannot be used)

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

It is best to use iterator traversal.

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>