Java编程:删除 List 元素的三种正确方法
删除 List 中的元素会产生两个问题:
- 删除元素后 List 的元素数量会发生变化;
- 对 List 进行删除操作可能会产生并发问题;
我们通过代码示例演示正确的删除逻辑
package com.ips.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ArrayListRemove {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("beijing");
list.add("shanghai");
list.add("shanghai");
list.add("guangzhou");
list.add("shenzhen");
list.add("hangzhou");
remove11(list, "shanghai");
}
private static void print(List<String> list){
for (String item : list) {
System.out.println("元素值:" + item);
}
}
/*
* 错误
*/
public static void remove11(List<String> list, String target){
int size = list.size();
for(int i = 0; i < size; i++){
String item = list.get(i);
if(target.equals(item)){
list.remove(item);
}
}
print(list);
}
/*
* 错误
*/
public static void remove12(List<String> list, String target){
for(int i = 0; i < list.size(); i++){
String item = list.get(i);
if(target.equals(item)){
list.remove(item);
}
}
print(list);
}
/*
* 正确
*/
public static void remove13(List<String> list, String target){
int size = list.size();
for(int i = size - 1; i >= 0; i--){
String item = list.get(i);
if(target.equals(item)){
list.remove(item);
}
}
print(list);
}
/*
* 正确
*/
public static void remove14(List<String> list, String target){
for(int i = list.size() - 1; i >= 0; i--){
String item = list.get(i);
if(target.equals(item)){
list.remove(item);
}
}
print(list);
}
/*
* 错误
*/
public static void remove21(List<String> list, String target){
for(String item : list){
if(target.equals(item)){
list.remove(item);
}
}
print(list);
}
/*
* 正确
*/
public static void remove22(ArrayList<String> list, String target) {
final CopyOnWriteArrayList<String> cowList = new CopyOnWriteArrayList<String>(list);
for (String item : cowList) {
if (item.equals(target)) {
cowList.remove(item);
}
}
print(cowList);
}
/*
* 错误
*/
public static void remove31(List<String> list, String target){
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String item = iter.next();
if (item.equals(target)) {
list.remove(item);
}
}
print(list);
}
/*
* 正确
*/
public