Πέμπτη, 2 Απριλίου 2009

How to remove elements from an array

Problem

I have an array, e.g.

String strArray[] = new String[3];

and I 'd like to remove elements that satisfy a certain condition.

You could write something like:

List lstStrings = Arrays.asList(strArray);
for (int i=
lstStrings.size()-1; i>=0; i--) {
   String s =  (String)
lstStrings.get(i);
   if (s.equals("target")) {
      
lstStrings.remove(i);
   }
}


and you 'll get a

java.lang.UnsupportedOperationException at java.util.AbstractList.remove

What's wrong? Well, the problem lies in this command:

List lstStrings = Arrays.asList(strArray);

The result of
Arrays.asList is an Arrays$ArrayList (and not an ArrayList) which is immutable and doesn't provide for a remove method.

Solution

List lstStrings = new ArrayList(Arrays.asList(strArray));