Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element from java.util.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...

like image 780
marioosh Avatar asked Nov 22 '10 09:11

marioosh


People also ask

How do I remove a few element from a list in Java?

The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

Can we remove the value from list in Java?

There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.

How do you remove an element from an ArrayList in Java?

Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).

How do I remove an object from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.


2 Answers

Unfortunately, not all lists allow you to remove elements. From the documentation of 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);
        }
     }
}
like image 118
aioobe Avatar answered Oct 13 '22 05:10

aioobe


Its simply means that the underlying List implementation is not supporting remove operation.

NOTE: List doesn't have to be a ArrayList. It can be any implementation and sometimes custom.

like image 20
Adeel Ansari Avatar answered Oct 13 '22 05:10

Adeel Ansari