如何从 java.util.List 中删除元素?
每次我在 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);
}
}
}
Stacktrace:
java.lang.UnsupportedOperationException
java.util.AbstractList.remove(AbstractList.java:144)
model.entities.Product.removeImage(Product.java:218)
...
我发现我需要使用比 List 接口更精确的类,但是 ORM 示例中的每个地方都使用了 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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,并非所有列表都允许您删除元素。来自
List.remove(int index)
的文档:除了创建一个与原始列表具有相同元素的新列表,并从这个新列表中删除这些元素之外,您无能为力。像这样:
Unfortunately, not all lists allow you to remove elements. From the documentation of
List.remove(int index)
: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:
它只是意味着底层
List
实现不支持删除操作。注意:
List
不必是ArrayList
。它可以是任何实现,有时是自定义的。Its simply means that the underlying
List
implementation is not supporting remove operation.NOTE:
List
doesn't have to be aArrayList
. It can be any implementation and sometimes custom.将列表转换为数组列表不会改变任何事情,对象本身仍然是一个列表,因此您只能使用列表属性,
您应该尝试使用新的 ArrayList 创建它
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