ArrayList与HashMap遍历删除元素,HashMap与ArrayList的clone体修改之间影响

前言

       最近做项目,需要一边遍历一边删除list与map,主要是ArrayList与HashMap。发现list与map删除报错了。而笔者同时需要保留旧的list与map,并执行增删改操作时,使用克隆的方式,然而克隆map与list,发现引用对象在map或者list是浅克隆,即克隆引用或者指针。

笔者环境:Oracle JDK8

 

1. 遍历删除

 

1.1 ArrayList遍历删除

笔者查询发现只能通过迭代器删除。否则报错java.util.ConcurrentModificationException。

public class IteratorTest {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("111");
        list.add("222");
        list.add("333");
        list.add("444");

        for (String str : list) {
            if ("222".equals(str)) {
                list.remove(str);
            }
        }
        System.out.println(list);
    }
}

笔者发现ArrayList的list.remove方法没问题啊

public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

仔细发现modCount++; 这句代码尤其要注意,这就是造成问题的诱因。

 

当笔者查看异常堆栈时

想起来foreach是执行迭代器语句,反编译一下,果然,其实使用下标迭代是可以删除的,ArrayList就是数组嘛,注意一下size判断循环条件就可以了。

源码分析,在ArrayList中,next方法,迭代器是ArrayList内部类实现的

这个check方法,很简单,简单粗暴抛异常。

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

这个modCount是ArrayList的全局变量,而expectedModCount是迭代器初始化时copy一份当时的modCount,当remove时

modCount++;

而迭代器的值初始化就固定了,所以值不相等,抛异常了,next进行不下去了。

解决办法:

①不用迭代器,下标删除,注意删除后size改变,判定条件也要改变

public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("111");
        list.add("222");
        list.add("333");
        list.add("444");

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

②迭代器提供的删除方法

public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("111");
        list.add("222");
        list.add("333");
        list.add("444");

        Iterator var2 = list.iterator();

        while(var2.hasNext()) {
            String str = (String)var2.next();
            if ("222".equals(str)) {
                var2.remove();
            }
        }
        System.out.println(list);
    }

解析源码,迭代器会把modCount同步过来,expectedModCount = modCount;

public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

不过,频繁增删改的list不推荐使用ArrayList,LinkedList更为方便,效率更高,当然这个问题仍然存在,还是要使用这2种方法处理。

1.2 HashMap同理

 

2. 克隆后增删改

 

2.1 HashMap克隆

Person类省略

package com.feng.clone;

import java.util.HashMap;
import java.util.Map;

public class MapCloneTest {

    public static void main(String[] args) {
        HashMap<String, Person> map = new HashMap<>();
        Person p1 = new Person();
        p1.setName("tom");
        p1.setAge(12);

        Person p2 = new Person();
        p2.setAge(15);
        p2.setName("JIM");

        map.put("person1", p1);
        map.put("person2", p2);

        HashMap<String, Person> mapClone = (HashMap<String, Person>) map.clone();
        for (Map.Entry<String, Person> entry : map.entrySet()) {
            mapClone.get(entry.getKey()).setName("aaaaaaaa");
            mapClone.remove(entry.getKey());
            Person p3 = new Person();
            p3.setAge(88);
            p3.setName("kkkk");
            mapClone.put("person3", p3);

            System.out.println(entry.getKey() + "" + entry.getValue());
        }
    }
}

运行发现,克隆map修改会影响本体map的bean,增加删除不会影响本体map

Connected to the target VM, address: '127.0.0.1:51147', transport: 'socket'
person2Person(name=aaaaaaaa, age=15)
person1Person(name=aaaaaaaa, age=12)
Disconnected from the target VM, address: '127.0.0.1:51147', transport: 'socket'

 

原理分析

看看HashMap的clone方法

public Object clone() {
        HashMap<K,V> result;
        try {
            //1.clone
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
        //2.reinit
        result.reinitialize();
        //3.copy table[]
        result.putMapEntries(this, false);
        return result;
    }

void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        threshold = 0;
        size = 0;
    }

可以看出

①直接clone的hashmap

②重新初始化

③复制本体map的table[]数组

    /**
     * Implements Map.putAll and Map constructor.
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            //循环遍历设置,但是只是引用,对象并未深度克隆
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

 

2.2 ArrayList克隆

package com.feng.clone;

import java.util.ArrayList;

public class ArrayListClone {
    public static void main(String[] args) {
        ArrayList<Person> list = new ArrayList<>();
        Person p1 = new Person();
        p1.setName("tom");
        p1.setAge(12);

        Person p2 = new Person();
        p2.setAge(15);
        p2.setName("JIM");
        list.add(p1);
        list.add(p2);

        ArrayList<Person> listClone = (ArrayList<Person>) list.clone();
        for (Person p : list) {
            listClone.get(0).setName("aaaaaaaa");
            listClone.remove(p);
            Person p3 = new Person();
            p3.setAge(88);
            p3.setName("kkkk");
            listClone.add(p3);

            System.out.println(p);
        }
    }
}

运行示例,可以看出跟map相同的现象,仅是arraylist克隆,对象只克隆引用

Person(name=aaaaaaaa, age=12)
Person(name=aaaaaaaa, age=15)

Process finished with exit code 0

ArrayList的clone原理分析

public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

很简单,直接克隆arraylist,然后复制数组,里面的元素仅复制引用

 

总结

       笔者在使用HashMap和ArrayList遍历删除元素的时候,也想到了copOnWriteList,但是Map没法实现,并且笔者的需求有新旧map和list只能修改新的map或者list,所以想到了克隆,但是HashMap和ArrayList的元素bean未克隆,笔者必须取出bean,然后对bean克隆然后设置到新的Map或者list中,HashMap和ArrayList是浅克隆,深克隆推荐序列化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章