UnsupportedOperationException at java.util.AbstractList.add

前端 未结 6 2006
误落风尘
误落风尘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 00:27

    List is Interface and you can not Add value in it until it is instance of ArrayList(interface should be implemented by some class)

    For Example:

        List test = new ArrayList<>();
        test.add(new Integer(2));
    
        ArrayList test2 = new ArrayList<>();
        test2.add(new Integer(2));
    
        List 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
    While in test3 it is just empty list so you can not add element in it.

    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.

     Map> itemStockMap = Collections.synchronizedMap(new HashMap>());
    

提交回复
热议问题