marioosh
marioosh

Reputation: 28556

How to remove element from java.util.List?

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...

Upvotes: 10

Views: 33725

Answers (3)

Jason Rogers
Jason Rogers

Reputation: 19344

Casting your list to array list won't change a thing, the object itself stays a List and therefore you only can use the List properties

what you should try is to create it with new ArrayList

Upvotes: 2

aioobe
aioobe

Reputation: 420951

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);
        }
     }
}

Upvotes: 23

Adeel Ansari
Adeel Ansari

Reputation: 39897

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.

Upvotes: 7

Related Questions