JavaEE--集合--删除List中指定元素

一、Java 循环删除list中指定元素

  1. 增强for循环删除指定元素
    @Test
    public void test(){
        String[] strs={"a", "b", "c", "f", "b", "e", "d"};
        List list = new ArrayList<>(Arrays.asList(strs));
        for (String s : list) {
            System.out.println("------" + s + "------");
            if ("b".equals(s)) {
                list.remove(s);
            }
        }
    }

结果:
java.util.ConcurrentModificationException


JavaEE--集合--删除List中指定元素_第1张图片
异常
  1. iterator删除指定元素
    @Test
    public void test(){
        String[] strs={"a", "b", "c", "f", "b", "e", "d"};
        List list = new ArrayList<>(Arrays.asList(strs));
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println("------"+next+"------");
            if ("b".equals(next)) {
                iterator.remove();
            }
        }
        System.out.println(list.toString());
    }
  1. CopyOnWriteArrayList
    @Test
    public void test(){
        List list = new ArrayList<>();
        list.add("aa");
        list.add("bb");
        list.add("cc");
        CopyOnWriteArrayList cowList = new CopyOnWriteArrayList<>(list);
        for (String str : cowList) {
            if ("aa".equals(str)) {
                cowList.remove(str);
            }
        }
        System.out.println(cowList.size());
    }
  1. 普通for循环
   for (int i = 0; i < list.size(); i++) {
            if ("2".equals(list.get(i))) {
                list.remove(i);
            }
        }
  1. 有重复元素的删除方法
        List list = new ArrayList<>();
        list.add("a");
        list.add("a");
        list.add("c");
        list.add("d");
        list.add("a");
        int i=0,size= list.size();
        for (; i < size; i++) {
            if ("a".equals(list.get(i))) {
                list.remove(i);
                i-=1;
                size-=1;
            }
        }
        for (String str : list) {
            log.info(str);
        }

你可能感兴趣的:(JavaEE--集合--删除List中指定元素)