UnsupportedOperationException at java.util.AbstractList.add

前端 未结 6 1999
误落风尘
误落风尘 2020-12-07 23:51

I\'m having issues getting a block of code to run properly. I\'m not entirely sure WHAT this code does (I\'m trying to get a plugin that\'s out of date to work properly with

6条回答
  •  鱼传尺愫
    2020-12-08 00:18

    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(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.

提交回复
热议问题