如何从 java.util.List 中删除元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4243786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove element from java.util.List?
提问by marioosh
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 ?
每次我在 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)
...
I see that i need to use more exact class than List interface, but everywehere in ORM examples List is used...
我看到我需要使用比 List 接口更精确的类,但是 ORM 示例中的每个地方都使用 List ......
采纳答案by aioobe
Unfortunately, not all lists allow you to remove elements. From the documentation of List.remove(int index)
:
不幸的是,并非所有列表都允许您删除元素。从文档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);
}
}
}
回答by Adeel Ansari
Its simply means that the underlying List
implementation is not supporting remove operation.
它只是意味着底层List
实现不支持删除操作。
NOTE: List
doesn't have to be a ArrayList
. It can be any implementation and sometimes custom.
注意:List
不必是ArrayList
. 它可以是任何实现,有时也可以是自定义的。
回答by Jason Rogers
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
您应该尝试使用新的 ArrayList 创建它