I have the following example java generics code which I modified as per suggestion of people on StackOverflow.Now the compilation is going through.
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);
}
}
I am getting the following runtime error.
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)