如何从java.util.List中删除元素?
每次我在java.util.List上使用.remove()方法时,都会得到错误UnsupportedOperationException。这让我发疯。对ArrayList进行强制转换没有帮助。怎么做如何从java.util.List中删除元素?,java,collections,Java,Collections,每次我在java.util.List上使用.remove()方法时,都会得到错误UnsupportedOperationException。这让我发疯。对ArrayList进行强制转换没有帮助。怎么做 @Entity @Table(name = "products") public class Product extends AbstractEntity { private List<Image> images; public void removeImage(i
@Entity
@Table(name = "products")
public class Product extends AbstractEntity {
private List<Image> images;
public void removeImage(int index) {
if(images != null) {
images.remove(index);
}
}
}
我知道我需要使用比列表接口更精确的类,但ORM示例列表中的所有内容都被使用 Its仅仅意味着底层的
List
实现不支持删除操作
注意:
List
不必是ArrayList
。它可以是任何实现,有时是自定义的。不幸的是,并非所有列表都允许您删除元素。从列表的文档中删除(int索引)
:
删除此列表中指定位置的元素(可选操作)
除了用与原始列表相同的元素创建一个新列表,并从这个新列表中删除元素之外,您没有什么可以做的。像这样:
public void removeImage(int index) {
if(images != null) {
try {
images.remove(index);
} catch (UnsupportedOperationException uoe) {
images = new ArrayList<Image>(images);
images.remove(index);
}
}
}
public void removeImage(int索引){
如果(图像!=null){
试一试{
图像。删除(索引);
}捕获(不支持操作异常uoe){
图像=新阵列列表(图像);
图像。删除(索引);
}
}
}
将列表强制转换为数组列表不会改变任何东西,对象本身保持一个列表,因此您只能使用列表属性
您应该尝试使用新的ArrayList创建它,您使用的是哪个列表实现,堆栈跟踪应该使这一点变得明显。看起来您使用的是某种ORM。您可能需要查阅其文档,以确定执行此操作的正确方法。是否确定您的列表中有条目?remove()应该是正确的方法。请发布完整的stacktrace,也许里面还有更多的信息。回答不错(+1),但我要挑战“不幸”这个词。我认为有些列表是不变的,这是一个特性。@Seanizer,呵呵,我同意你的看法!对于OP来说,我想这仍然是不幸的;)@但是列表是一个接口。。。这意味着,如果我们为一个具体的类实现这个接口,我们将实现所有的方法。。。在这种情况下,这怎么可能是可选的:“并非所有列表都允许您删除元素”。。。那么在这种情况下,它故意抛出“UnsupportedOperationException”?没错
throw new UnsupportedOperationException()
是List的有效实现。根据文档删除。我唯一要做的“改进”是让方法返回一个图像,这样契约将类似于List
(返回删除的项,如果找不到,则返回null)。
public void removeImage(int index) {
if(images != null) {
try {
images.remove(index);
} catch (UnsupportedOperationException uoe) {
images = new ArrayList<Image>(images);
images.remove(index);
}
}
}