0

I'm trying to order a list of time spans (represented as Time[] arrays with a start time and end time) by their start times. I'm trying to use the following nested loop to do so:

            for (Time[] span : workingList){
            Time[] compareTo = workingList.get(0);

                for (Time[] inSpan : workingList){
                    if (inSpan[0].before(compareTo[0])){
                    compareTo = inSpan;
                    }
                }
            workingList.remove(compareTo);
            toReturn.add(compareTo);
        }

    }

but it is throwing a java.util.ConcurrentModificationException at the line for (Time[] span : workingList) (the one on top). I've never seen this exception before, can someone please explain to me what it means and what causes it.

I'm also open to suggestions of better algorithms for this.

drew moore
  • 31,565
  • 17
  • 75
  • 112
  • For future reference: when you have a question about an Exception, you can always consult the documentation. If you google "_Java 7 ConcurrentModificationException_" the first result will bring you to the documentation. If you read the overview at the top of that page, it explains this exact scenario. – jahroy Mar 16 '13 at 01:15

2 Answers2

6
workingList.remove(compareTo);

You are modifying a collection while iterating on it.

You should use something like:

ListIterator<Time[]> it = workingList.listIterator();

while (it.hasNext()) {
  Time[] time = it.next();
  ..
  it.remove();
}

There are ways also without using the list iterator but this seems the more correct.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Another option is to build a list of items you want to remove **WHILE** iterating, and to remove them **AFTER** iterating. – jahroy Mar 16 '13 at 01:12
  • It mainly depends on the algorithm, in the OP case build a temporary list could be the only option if the element he is deleting is not always the same on which it is iterating. – Jack Mar 16 '13 at 01:14
1

My suggestion is that you use Collections.sort() for ordering lists. It does the sorting for you, and makes it a lot more readable what you are trying to do. You'll need to specify your own Comparator when calling the method - as such:

    Collections.sort(workingList,new Comparator<Time[]>() {
        @Override
        public int compare(Time[] time1, Time[] time2) {
            return time1[0].before(time2[0]);
        }
    });

This will sort workingList as your specs.

ddmps
  • 4,350
  • 1
  • 19
  • 34