我有下面的示例java泛型代码,我根据StackOverflow上的人的建议进行了修改。编译正在进行。java泛型运行时error.java.util.ConcurrentModificationException
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)
你是说迭代器不应该是一个实例变量。每一个方法应该创建一个自己的构造函数的副本?这是一种被接受/推荐的编码习惯吗? – liv2hak
迭代器只能使用一次。在使用时您无法修改集合。当你想迭代时,你需要一个新的迭代器到集合中,这很简单。大多数情况下,你甚至不需要迭代器:for-each循环会为你创建一个:'for(T element:tList)...' –