Everytime i use .remove() method on java.util.List i get error UnsupportedOperationException. It makes me crazy. Casting to ArrayList not helps. How to do that ?
@Entity
@Table(name = "products")
public class Product extends AbstractEntity {
private List<Image> images;
public void removeImage(int index) {
if(images != null) {
images.remove(index);
}
}
}
Stacktrace:
java.lang.UnsupportedOperationException
java.util.AbstractList.remove(AbstractList.java:144)
model.entities.Product.removeImage(Product.java:218)
...
I see that i need to use more exact class than List interface, but everywehere in ORM examples List is used...
The List provides removeAll() method to remove all elements of a list that are part of the collection provided.
There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.
Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).
There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.
Unfortunately, not all lists allow you to remove elements. From the documentation of List.remove(int index)
:
Removes the element at the specified position in this list (optional operation).
There is not much you can do about it, except creating a new list with the same elements as the original list, and remove the elements from this new list. Like this:
public void removeImage(int index) {
if(images != null) {
try {
images.remove(index);
} catch (UnsupportedOperationException uoe) {
images = new ArrayList<Image>(images);
images.remove(index);
}
}
}
Its simply means that the underlying List
implementation is not supporting remove operation.
NOTE: List
doesn't have to be a ArrayList
. It can be any implementation and sometimes custom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With