Sorting out Collections

The for-each loop introduced with 1.5 is very useful, unless you iterate over a collection to sort it out.

...
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
   if (condition) iterator.remove();
}

In most cases this woks well, but there is the corner-case where the backing collection does not support the remove operation. This is the case if the collection was an array that was converted through the Arrays class:

List list = Arrays.asList(array)

This produces a fixed size list. As it is impossible to remove an element from the array (and thus reducing its size) it is not possible to remove an element from the list. There is an easy workaround: Create a new dynamic List from the static List:

List list = new ArrayList(Arrays.asList(array))

Schreibe einen Kommentar