1

This method returns a list of employee objects using Cayenne SelectQuery

List<Employee> getEmployees() {
  ...
  return getObjectContext().performQuery(query);
}

Now, I'm looping through the results

List<Employee> employees = getEmployees();

// test loop 1
for (Employee employee : employees) {
  //print out employee name
}

for (Employee employee : employees) {
  //print out employee name
  if (matchesSomeCondition) {
    employees.remove(employee);
  }
}

// test loop 2
for (Employee employee : employees) {
  //print out employee name
}

In test loop 1, it would show for example:

-John Smith
-Jane Doe
-Roger Wilco

In the actual removal loop, it would omit some people:

-John Smith
-Roger Wilco

Then in test loop 2 it would output everyone:

-John Smith
-Jane Doe
-Roger Wilco

When I change the removal loop to:

List<Employee> badEmployees = new ArrayList<Employee>();
for (Employee employee : employees) {
  //print out employee name
  if (matchesSomeCondition) {
    badEmployees.add(employee);
  }
}
employee.removeAll(badEmployees);

Then the loop works fine. I just don't understand why I did not get an error or exception in the first example. Even more bizarre is why the results are different in each of the test loop.

Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
Tuan
  • 1,476
  • 13
  • 23

2 Answers2

0

Java for-each loop isn't designed for manipulating the List it is iterating on. You need access to the Iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove().

Hence, the approach you have chosen, thats the only way (with a for-each).

You can read more about it here.

Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
  • I realized that I shouldn't be removing from the list while iterating through it, that's why I changed the code to remove after. But I did not get an exception like this example: [link]http://stackoverflow.com/questions/5113016/getting-a-concurrentmodificationexception-thrown-when-removing-an-element-from-a[/link] – Tuan Apr 24 '13 at 04:23
0

I was just looking at my old questions and saw this one still unanswered.

Removing employee triggered a callback in Cayenne that in turn added the employee back to the list.

Tuan
  • 1,476
  • 13
  • 23