UnsupportedOperationException at java.util.AbstractList.add UnsupportedOperationException at java.util.AbstractList.add java java

UnsupportedOperationException at java.util.AbstractList.add


You're using Arrays.asList() to create the lists in the Map here:

itemStockMap.put(item.getInfo(), Arrays.asList(item.getStock()));  

This method returns a non-resizable List backed by the array. From that method's documentation:

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

In order to use a resizable List (and actually copy the contents), use the following:

itemStockMap.put(        item.getInfo(),        new ArrayList<Integer>(Arrays.asList(item.getStock()))); 

Note: in general, when seeing that UnsupportedOperationException is being thrown by add, etc. it's typically an indication that some code is trying to modify a non-resizable or unmodifiable collection.

For example, Collections.emptyList or Collections.singletonList (which return unmodifiable collections) may be used as optimizations but accidentally be passed into methods that try to modify them. For this reason it's good practice for methods to make defensive copies of collections before modifying them (unless of course modifying the collection is a method's intended side effect) - that way callers are free to use the most appropriate collection implementation without worrying about whether it needs to be modifiable.


I think I've worked out your problem. Arrays.asList(item.getStock()) returns a fixed size list based on the Array passed to it.

This means you cannot add more elements to it.

Instead you should do new ArrayList(Arrays.asList(item.getStock())).

This way you are creating a new list that you can add to.


The problem is you are creating your lists with Arrays.asList. Per the javadoc provided, the returned list is a Fixed Size, therefore add would be unsupported. Wrap the returned list in a copy constructor for arrayList and you should be set.