[英]How to replace an element in a java.util.List with an element of another type?
[英]How to remove element from 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);
}
}
}
堆棧跟蹤:
java.lang.UnsupportedOperationException
java.util.AbstractList.remove(AbstractList.java:144)
model.entities.Product.removeImage(Product.java:218)
...
我看到我需要使用比List接口更精確的類,但是在ORM示例列表中的每一個都使用...
不幸的是,並非所有列表都允許您刪除元素。 從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);
}
}
}
它只是意味着底層的List
實現不支持刪除操作。
注意: List
不必是ArrayList
。 它可以是任何實現,有時是自定義的。
將列表轉換為數組列表不會改變事物,對象本身保持List,因此您只能使用List屬性
你應該嘗試用新的ArrayList創建它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.