java list删除元素总结

靠谱的有4个方式,ArrayList删除的方式的目标索引往前一位,最后一个元素置null。

1、从前往后变量,i--;size--;

/*
 * 正确
 */
public static void remove10(List list, String target) {
    for (int i = 0, size = list.size(); i < size; i++) {
        String item = list.get(i);
        if (target.equals(item)) {
            list.remove(item);
            // or list.remove(i);
            size--;
            i--;
        }
    }
    print(list);
}

2、从后往前,不用做额外的下标、大小校验;

/*
 * 正确
 */
public static void remove14(List list, String target){
    for(int i = list.size() - 1; i >= 0; i--){
        String item = list.get(i);
        System.out.println("i:"+i+",item:"+item);
        if(target.equals(item)){
            list.remove(item);
        }
    }
    print(list);
}

3、迭代器iterator

/*
 * 正确
 */
public static void remove32(List list, String target){
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        String item = iter.next();
        if (item.equals(target)) {
            iter.remove();
        }
    }
    print(list);
}

4、CopyOnWriteArrayList,保证了同步,不是下标移动的方式删除

/*
 * 正确
 */
public static void remove22(ArrayList list, String target) {
    final CopyOnWriteArrayList cowList = new CopyOnWriteArrayList(list);
    for (String item : cowList) {
        if (item.equals(target)) {
            cowList.remove(item);
        }
    }
    print(cowList);
}

 

参考:https://blog.csdn.net/claram/article/details/53410175#commentsedit

https://blog.csdn.net/DeMonliuhui/article/details/75057512

你可能感兴趣的:(java)