开发者

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.UnsupportedOperationExc开发者_如何转开发eption
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...


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜