I found this statement, if the thread modifies the collection directly, when iterates through the collection using a fail-safe iterator, the iterator will throw this exception. at http://download.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html .
I found that simultaneous modification is even selected below the code
List<Employee> lista= new ArrayList(); Employee emp1=new Employee(); Employee emp2=new Employee(); Employee emp3=new Employee(); lista.add(emp1); lista.add(emp2); lista.add(emp3); for(Employee emp:lista) { emp2.setEmpId(2); lista.remove(emp2); }
Question1: - Can I say that loop gain also uses a failover iterator inside? Although, when I execute the code below, it works great
for(int i=0;i<lista.size();i++) { Employee empTemp=lista.get(i); lista.remove(emp2); }
Question2: - Another question when the expression says
if the thread modifies the collection
My guess is that modifying here means deleting or adding not to update an item inside the collection for the list interface, while it also includes modifying the element for the given interface. Correctly? At least the programs I tried are with them.
Edit
As for the set, I doubt my statement above, that is, it throws a parallel modification exception when we try to modify set while iterating.I tried to execute the code below, but it did not throw any exception.
HashSet<Employee> set1= new HashSet(); Employee emp4=new Employee(); Employee emp5=new Employee(); Employee emp6=new Employee(); set1.add(emp4); set1.add(emp5); set1.add(emp6); Iterator iter1=set1.iterator(); while(iter1.hasNext()) { Employee emp12=(Employee)iter1.next(); System.out.println(""); emp5.setEmpId(2); }
Ideally according to the instructions, if the set changes at any time after creating the iterator at http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html it should throw a parallel modification exception, but this not this way. Do not know why?
java
M sach
source share