I am getting an UnsupportedOperationException when calling add() in the following code:

Collection<MyClass> myClass = method();
MyClass newObject = new MyClass();
myClass.add(newObject);

method() returns Collection<MyClass>.

Also, what should I do if method returns null or an empty Collection?

有帮助吗?

解决方案

This error means that the method is choosing to return a read-only collection. If you want to add additional items, you will need to create a new collection from it. For example:

List<Thing> things = new ArrayList<>(method());
things.add(new Thing());

其他提示

Per the javadocs, some Collections do not support the add() method and since Collection is just an interface, you need to look to see what implementation type the Collection is. You can do this in a debugger or with myClass.getClass().getName()

Once you find out what type method() returns, you should either (1) create a class that extends method()'s type and implements the add() method, initializing myClass to an object of that class. (2) Cast method()'s return object to another type of class that implements add(). I recommend (1) to preserve the other functionalities in method()'s return class.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top