0

我有以下示例 java 泛型代码,我根据 StackOverflow 上的人的建议对其进行了修改。现在编译正在进行中。

import java.util.*;

public class GenericBox<T>
{

        private List<T> tList;
        private Iterator<T> itor;

        public GenericBox()
        {
                tList = new ArrayList<T>();
                itor = tList.listIterator();
        }

        public void insert(T element)
        {
                tList.add(element);
        }

        public T retrieve()
        {
                if(itor.hasNext())
                {
                        return itor.next();
                }
                return null;
        }

        public static void main (String [] args)
        {

                GenericBox <String> strbox = new GenericBox<String>();
                GenericBox <String> intbox = new GenericBox<String>();

                strbox.insert(new String("karthik"));
                strbox.insert(new String("kanchana"));
                strbox.insert(new String("aditya"));


                String s = strbox.retrieve();
                System.out.println(s);

                s = strbox.retrieve();
                System.out.println(s);

                s = strbox.retrieve();
                System.out.println(s);
        }
}

我收到以下运行时错误。

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
    at java.util.ArrayList$Itr.next(ArrayList.java:791)
    at GenericBox.retrieve(GenericBox.java:24)
    at GenericBox.main(GenericBox.java:40)
4

2 回答 2

5

这与泛型无关,与您直接修改集合(in insert)然后尝试使用在插入之前创建的迭代器这一事实有关。不要这样做。

来自以下文档ArrayList

此类的 iterator 和 listIterator 方法返回的迭代器是快速失败的:如果在创建迭代器后的任何时间对列表进行结构修改,除了通过迭代器自己的 remove 或 add 方法之外的任何方式,迭代器将抛出 ConcurrentModificationException。因此,面对并发修改,迭代器快速而干净地失败,而不是在未来不确定的时间冒任意的、非确定性的行为。

如果您必须保留迭代器,请使用来添加新值:

private ListIterator<T> itor; // Not just Iterator<T>; you need the add method

public void insert(T element)
{
    itor.add(element);
}

不过最好不要保留迭代器——除了直接循环之外,使用迭代器很少是个好主意

于 2013-07-26T22:40:42.110 回答
1

你得到这个异常是因为列表在迭代器的创建和它的使用之间被修改了。您应该只iterator()在您真正想要遍历列表时调用。不是以前。而且您不应该将迭代器存储在实例字段中。仅在局部变量中。

于 2013-07-26T22:41:41.830 回答