-1

This link says that I can remove a string by directly addressing it with the parameter, like:

myList.remove("myString");

but trying to do this I get the java.lang.UnsupportedOperationException exception.

UPDATE The code I use to create and fill the list:

List<String> myList = new ArrayList<>(myArray.length);
for (String str : myArray) {
    myList.add(str);
}

The code I get the exception while executing:

if (myList.contains("specificString"))
    myList.remove("specificString");
}

How can I remove this element then without using the for loop or an index?

Community
  • 1
  • 1
Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63

2 Answers2

1

Assuming yours a ArrayList, ideally you could remove the object from a list using the list.remove(obj) as you did unless the list is unmodifiable as shown below:

    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    System.out.println(list); // [a,b,c]

    list.remove("a");
    System.out.println(list); // [b,c]

    List<String> unmodifiable = Collections.unmodifiableList(list);
    unmodifiable.remove("b"); // UnsupportedOperationException
HJK
  • 1,382
  • 2
  • 9
  • 19
0

The List interface (java.util.List) includes a method remove(object). Not all implementations support that method though. For implementations that don't implement this method you get this exception. It is even documented here:

https://docs.oracle.com/javase/7/docs/api/java/util/List.html#remove(java.lang.Object)

If you use ArrayList then you should be fine. If you use some custom fixed size implementation or some other implementation that doesn't suppor that operation then you cannot use this method.

Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23