简体   繁体   English

java.util.AbstractList.add 处的 UnsupportedOperationException

[英]UnsupportedOperationException at java.util.AbstractList.add

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 our server), I just know every 20 minutes it runs and throws out an error.我不完全确定这段代码的作用(我正在尝试获取一个过时的插件以在我们的服务器上正常工作),我只知道它每 20 分钟运行一次并抛出一个错误。 Here's the section of code where the issue is happening:这是发生问题的代码部分:

public class DynamicThread extends Thread {
private LocalShops plugin = null;


public DynamicThread(ThreadGroup tgroup, String tname, LocalShops plugin) {
    super(tgroup, tname);
    this.plugin = plugin;
}

public void run() {
    Map<ItemInfo, List<Integer>> itemStockMap = Collections.synchronizedMap(new HashMap<ItemInfo, List<Integer>>());
    
    //Dump all the shop stock data into the map.
    for ( Shop shop : plugin.getShopManager().getAllShops() ) {
        for ( InventoryItem item : shop.getItems() ) {
            if (itemStockMap.containsKey(item.getInfo()))
                itemStockMap.get(item.getInfo()).add(item.getStock()); //Where error happens
            else
                itemStockMap.put(item.getInfo(), Arrays.asList(item.getStock()));     
        }
    }
    for(ItemInfo item : itemStockMap.keySet()) {
        List<Integer> stockList = GenericFunctions.limitOutliers(itemStockMap.get(item));
        //remove the map before re-adding it
        if (DynamicManager.getPriceAdjMap().containsKey(item)) 
            DynamicManager.getPriceAdjMap().remove(item);
        
        //Get the overall stock change for a given item and then calculate the adjustment given the volatility
        int deltaStock = GenericFunctions.getSum(stockList) - Config.getGlobalBaseStock();
        DynamicManager.getPriceAdjMap().put(item, GenericFunctions.getAdjustment(Config.getGlobalVolatility(), deltaStock)); 
    }
    
    Bukkit.getServer().getScheduler().callSyncMethod(plugin, plugin.getShopManager().updateSigns());
}

} }

The error happens from line 42, which is:错误发生在第 42 行,即:

                itemStockMap.get(item.getInfo()).add(item.getStock());

The error it outputs happens every 20 minutes twice with 2 seconds in between.它输出的错误每 20 分钟发生两次,中间间隔 2 秒。

2012-02-16 16:53:25 [INFO] Launch Dynamic Thread
2012-02-16 16:53:25 [SEVERE] Exception in thread "dynamic" 
2012-02-16 16:53:25 [SEVERE] java.lang.UnsupportedOperationException
2012-02-16 16:53:25 [SEVERE] at java.util.AbstractList.add(AbstractList.java:131)
2012-02-16 16:53:25 [SEVERE] at java.util.AbstractList.add(AbstractList.java:91)
2012-02-16 16:53:25 [SEVERE] at       com.milkbukkit.localshops.threads.DynamicThread.run(DynamicThread.java:42)

2012-02-16 16:53:27 [INFO] Launch Dynamic Thread
2012-02-16 16:53:27 [SEVERE] Exception in thread "dynamic" 
2012-02-16 16:53:27 [SEVERE] java.lang.UnsupportedOperationException
2012-02-16 16:53:27 [SEVERE] at java.util.AbstractList.add(AbstractList.java:131)
2012-02-16 16:53:27 [SEVERE] at java.util.AbstractList.add(AbstractList.java:91)
2012-02-16 16:53:27 [SEVERE] at     com.milkbukkit.localshops.threads.DynamicThread.run(DynamicThread.java:42)

You're using Arrays.asList() to create the lists in the Map here: 您正在使用Arrays.asList()在此处创建Map的列表:

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

This method returns a non-resizable List backed by the array. 此方法返回由数组支持的不可调整大小的List 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: 要使用可调整大小的List (并实际复制内容),请使用以下命令:

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. 注意:通常,当看到add等抛出UnsupportedOperationException时,通常表明某些代码正在尝试修改不可调整大小或不可修改的集合。

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. 例如, Collections.emptyListCollections.singletonList (返回不可修改的集合)可以用作优化,但不小心会传递给尝试修改它们的方法。 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. Arrays.asList(item.getStock())根据传递给它的Array返回一个固定大小的列表

This means you cannot add more elements to it. 这意味着您无法向其添加更多元素。

Instead you should do new ArrayList(Arrays.asList(item.getStock())) . 相反,你应该做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 . 问题是您使用Arrays.asList创建列表。 Per the javadoc provided, the returned list is a Fixed Size, therefore add would be unsupported. 根据提供的javadoc,返回的列表是固定大小,因此不支持添加。 Wrap the returned list in a copy constructor for arrayList and you should be set. 将返回的列表包装在arrayList的复制构造函数中,您应该进行设置。

List is Interface and you can not Add value in it until it is instance of ArrayList(interface should be implemented by some class) 列表是接口,你不能在其中添加值,直到它是ArrayList的实例(接口应该由某个类实现)

For Example: 例如:

    List<Integer> test = new ArrayList<>();
    test.add(new Integer(2));

    ArrayList<Integer> test2 = new ArrayList<>();
    test2.add(new Integer(2));

    List<Integer> test3 = Collections.EMPTY_LIST;
    test3.add(new Integer(2));

Here Object test and test2 are perfect, because they are object of ArrayList class so addition is possible 这里Object 测试test2是完美的,因为它们是ArrayList类的对象,所以可以添加
While in test3 it is just empty list so you can not add element in it. test3中,它只是空列表,因此您无法在其中添加元素。

I was also doing the same mistake. 我也犯了同样的错误。

Here is my Suggestion Use ArrayList when you have to do operations like add or remove, Use List only for reference purpose. 当您必须执行添加或删除操作时,我的建议使用ArrayList,仅用于参考目的。

 Map<ItemInfo, ArrayList<Integer>> itemStockMap = Collections.synchronizedMap(new HashMap<ItemInfo, ArrayList<Integer>>());

The problem is in the class of the list object that is returned by the get call. 问题出在get调用返回的列表对象的类中。 It doesn't override the add methods appropriately, and your code is therefore using the placeholder method provided by AbstractList . 它没有适当地覆盖add方法,因此您的代码使用AbstractList提供的占位符方法。

There's not much more we can say without knowing what the list class is, and (if it is custom code) seeing the source code. 如果不知道列表类是什么,并且(如果它是自定义代码)看到源代码,我们可以说更多。

In my case I had used: 就我而言,我用过:

List<File> removeFilesList= Collections.emptyList();

which made my File arraylist abstract. 这使我的文件arraylist摘要。 Used instead: 改为使用:

List<File> removeFilesList= new ArrayList<>();

And the error was fixed. 错误是固定的。

I was using a getter to get the list, but it was returning the fixed size of the list and you can't add a new element so,我正在使用 getter 来获取列表,但它返回的是列表的固定大小,因此你不能添加新元素,

Instead you should do相反,你应该做

new ArrayList(Arrays.asList(item.getStock()))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javax.el.E​​LException:java.util.AbstractList.add中的java.lang.UnsupportedOperationException - javax.el.ELException: java.lang.UnsupportedOperationException at java.util.AbstractList.add java.util.AbstractList.remove上的java.lang.UnsupportedOperationException - java.lang.UnsupportedOperationException at java.util.AbstractList.remove java.util.AbstractList.remove 处的 java.lang.UnsupportedOperationException(未知来源) - java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source) java.util.Abstractlist中的Java ConcurrentModificationException - Java ConcurrentModificationException at java.util.Abstractlist java.util.AbstractList $ Itr.checkForComodification错误 - java.util.AbstractList$Itr.checkForComodification Error java.util.AbstractList $ Itr.checkForComodification三元事件 - java.util.AbstractList$Itr.checkForComodification Triple Events 在ArrayList上操作时,AbstractList.remove()中的UnsupportedOperationException - UnsupportedOperationException in AbstractList.remove() when operating on ArrayList 在列表上调用.sort时AbstractList UnsupportedOperationException - AbstractList UnsupportedOperationException when calling .sort on a List Xpages-在Java类&#39;java.util.AbstractList $ SimpleListIterator&#39;上调用方法&#39;next()&#39;时出错 - Xpages - Error calling method 'next()' on java class 'java.util.AbstractList$SimpleListIterator' Java List.add() UnsupportedOperationException - Java List.add() UnsupportedOperationException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM