0

Whenever I try to remove an element from a List using list.removeIf(condition) it throws UnsupportedOperationException:

public class Test 
{
    public static void main(final String[] args) 
    {
        String[] stringArray = new String[]{"A","B","C","D"}; 
        List<String> stringList = Arrays.asList(stringArray); 
        stringList.forEach(System.out::println); 
        stringList.removeIf((String string) -> string.equals("B")); 
        stringList.forEach(System.out::println); 
    }
}

Why is it not working?

Eran
  • 387,369
  • 54
  • 702
  • 768
T-Bag
  • 10,916
  • 3
  • 54
  • 118

2 Answers2

9

Arrays.asList returns a fixed sized List - backed by the array you pass in - so, just as you can't remove (or add) elements from an array, you can't remove (or add) elements from the List.

Use a java.util.ArrayList in order to be able to remove elements:

List<String> stringList = new ArrayList<>(Arrays.asList(stringArray)); 
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Array.asList method returns an ArrayList of type java.util.Arrays.ArrayList (which is read only and fixed size) and not the classic java.util.ArrayList (resizable and item-removable)

sreeroop
  • 64
  • 1
  • 9