ConcurrentModificationException产生原因的情况解析

来源:互联网 发布:2017年优化设计答案 编辑:程序博客网 时间:2024/05/21 08:51


产生这个异常,归根结底的原因是因为,一个list或者集合 在遍历的同时进行了 写或者删除操作,改变了 list的大小:

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;


        public boolean hasNext() {
            return cursor != size;
        } 

@SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }


        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();
            }
        }


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


 }

造成这个现象的原因:

1 简单直接的原因,遍历的时候进行了增 删操作

for (String str : list) {

list.add(s); 

or 

list.remove(0);

}

2. 还有一种情况 就是一个list 在多线程环境先,被不同的线程在遍历的同时,进行了增删操作

/**
 * 中文转汉语拼音
 * 支持多音字
 */
public class HanyuPinyinHelper {


    private static StringBuffer buffer;
    private static List<String> list;
    private static Properties p;
    private static boolean isSimple;


    static{
        buffer = new StringBuffer();
        list = new ArrayList<String>();
        p = new Properties();
        isSimple=false;
        try {
            p.load(new BufferedInputStream(HanyuPinyinHelper.class
                    .getResourceAsStream("/hanyu_pinyin.txt")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    public static String[] getHanyuPinyins(char c) {
        int codePointOfChar = c;
        String codepointHexStr = Integer.toHexString(codePointOfChar)
                .toUpperCase();
        String str = (String) p.get(codepointHexStr);
        return str.split(",");
    }


    /**
     * @param str 需要转换的字符串
     * @param isSimple true简拼,false全拼
     * @return 该字符串转换后的所有组合
     */
    public static List<String> hanyuPinYinConvert(String str,boolean isSimpleFlag) {
        if (str == null || "".equals(str))
            return null;
        isSimple=isSimpleFlag;
        list.clear();
        buffer.delete(0, buffer.length());
        convert(0, str);
        return list;
    }




    /**
     * @param str 需要转换的字符串
     * @return 该字符串转换后的所有组合,包含全拼和简拼
     */
    public static List<String> hanyuAllPinYinConvert(String str) {
        if (str == null || "".equals(str))
            return null;
        list.clear();
        buffer.delete(0, buffer.length());
        isSimple=true;
        convert(0, str);
        buffer.delete(0, buffer.length());
        isSimple=false;
        convert(0, str);
        return list;
    }


    private static void convert(int n, String str) {
        if (n == str.length()) {// 递归出口
            String temp=buffer.toString();
            if(!list.contains(temp)){
                list.add(buffer.toString());
            }
            return;
        } else {
            char c = str.charAt(n);
            if (0x3007 == c || (0x4E00 <= c && c <= 0x9FA5)) {// 如果该字符在中文UNICODE范围
                String[] arrayStrings = getHanyuPinyins(c);
                if (arrayStrings == null) {
                    buffer.append(c);
                    convert(n + 1, str);
                } else if (arrayStrings.length == 0) {
                    buffer.append(c);
                    convert(n + 1, str);
                } else if (arrayStrings.length == 1) {
                    if(isSimple){
                        if(!"".equals(arrayStrings[0])){
                            buffer.append(arrayStrings[0].charAt(0));
                        }
                    }else{
                        buffer.append(arrayStrings[0]);
                    }
                    convert(n + 1, str);
                } else {
                    int len;
                    for (int i = 0; i < arrayStrings.length; i++) {
                        len = buffer.length();
                        if(isSimple){
                            if(!"".equals(arrayStrings[i])){
                                buffer.append(arrayStrings[i].charAt(0));
                            }
                        }else{
                            buffer.append(arrayStrings[i]);
                        }
                        convert(n + 1, str);
                        buffer.delete(len, buffer.length());
                    }
                }
            } else {// 非中文
                buffer.append(c);
                convert(n + 1, str);
            }
        }
    }


    public static void main(String[] args) {
        List list1 = HanyuPinyinHelper.hanyuAllPinYinConvert("瞿乐底");
        System.out.println(list1);


    }


}


0 0
原创粉丝点击