每次我在java.util.List上使用.remove()方法我得到错误UnsupportedOperationException.这让我很疯狂.转换为ArrayList没有帮助.怎么做 ?
@Entity
@Table(name = "products")
public class Product extends AbstractEntity {
private List<Image> images;
public void removeImage(int index) {
if(images != null) {
images.remove(index);
}
}
}
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
java.lang.UnsupportedOperationException
java.util.AbstractList.remove(AbstractList.java:144)
model.entities.Product.removeImage(Product.java:218)
...
Run Code Online (Sandbox Code Playgroud)
我看到我需要使用比List接口更精确的类,但是在ORM示例列表中的每一个都使用...
aio*_*obe 23
不幸的是,并非所有列表都允许您删除元素.来自以下文件List.remove(int index):
删除此列表中指定位置的元素(可选操作).
除了创建一个与原始列表具有相同元素的新列表之外,您无法做很多事情,并从此新列表中删除元素.像这样:
public void removeImage(int index) {
if(images != null) {
try {
images.remove(index);
} catch (UnsupportedOperationException uoe) {
images = new ArrayList<Image>(images);
images.remove(index);
}
}
}
Run Code Online (Sandbox Code Playgroud)