BigBug
BigBug

Reputation: 6290

remove element from list of strings?

AH! I have a list of strings... and i just want to remove an element from the list if it is ""

but i keep causing the program to crash. How do i get around this? I made a list of arrays into a List of strings thinking i could remove it that way. Here is what i have:

        List<String>list;

        String[] f= new String[file.length()];
        f= file.split("<"); 

        list= Arrays.asList(f); 

        final Iterator<String> iter = list.iterator();
        while (iter.hasNext()) 
        {
            final String temp = iter.next();
            // TODO check for zero-length arrays
            if (temp.equals("")) 
            {
                iter.remove();
            }
        }

Error:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(Unknown Source)
        at java.util.AbstractList$Itr.remove(Unknown Source)
        at utilities.Validation.Validate(Validation.java:44)

After i convert it to a List, i can print the list just fine.. it's removing elements from it that becomes an problem...

Upvotes: 3

Views: 8496

Answers (3)

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

Arrays.asList produces a list that doesn't allow adding or removing elements.

If there is a lot elements to remove then here is a quick way to do that:

List<String> result = new ArrayList<String>();
for (String next : file) {
   if (next != null && next.length() != 0) result.add(next);
}

Upvotes: 0

Natix
Natix

Reputation: 14247

The reason why you were getting the exception has already been answered, but I add a little note about your code: You can remove all empty strings from a list in a much simpler way using the removeAll() method. You don't even have to check if the given array is empty, because this method can handle them.

String[] array = { "aa", "", "cc", "", "d" };
List<String> list = new ArrayList<String>(Arrays.asList(array));

list.removeAll(Collections.singleton(""));
System.out.println(list);

Which prints:

[aa, cc, d]

Upvotes: 1

Jeffrey
Jeffrey

Reputation: 44808

The List returned by Arrays#asList has a fixed size. Since removeing an element would modify the length, it is unsupported. If you want a List that allows removal of items, use new ArrayList<>(Arrays.asList(array));.

Upvotes: 13

Related Questions