This question already has answers here:
Java List.add() UnsupportedOperationException
                                
                                    (7个答案)
                                
                        
                2年前关闭。
            
        

我正进入(状态


  java.lang.UnsupportedOperationException


列表中的异常。

为什么会发生此异常?



List<String> smsUserList = new ArrayList<String>();
    if (event.getEventTemplate().equalsIgnoreCase(CommunicationConstants.MEMBER)) {
        String testNumbers = env.getRequiredProperty(CommunicationConstants.TEST_SMS_NUMBRES);
        String[] testSmsNumber = testNumbers.split(",");
        if (null != testSmsNumber && testSmsNumber.length > 1) {
            smsUserList = Arrays.asList(testSmsNumber);

        }

    }
    if (event.getEventTemplate().equalsIgnoreCase(CommunicationConstants.AGENT)) {
        String testNumbers = env.getRequiredProperty(CommunicationConstants.TEST_SMS_NUMBRES);
        String[] testSmsNumber = testNumbers.split(",");
        if (null != testSmsNumber && testSmsNumber.length > 1) {
            smsUserList = Arrays.asList(testSmsNumber);
        }
    }

    Set<SMSCommunicationRecipient> smsRecipientAll = event.getSmsCommunicationRecipient();
    for (SMSCommunicationRecipient smsRecipient : smsRecipientAll) {
        String smsRecipientValue = smsRecipient.getRecipientGroupId().getReferenceTypeValue();
        if (smsRecipientValue.equalsIgnoreCase(CommunicationConstants.MEMBER)) {
            List<String> memberContact = (List<String>) communicationInput
                    .get(CommunicationConstants.MEMBER_CONTACT_NUMBER_LIST);
            if (CollectionUtils.isNotEmpty(memberContact)) {
                for (String smsNumber : memberContact) {
                    smsUserList.add(smsNumber);
                }
            }
        }
        if (smsRecipientValue.equalsIgnoreCase(CommunicationConstants.AGENT)) {
            List<String> agentContact = (List<String>) communicationInput
                    .get(CommunicationConstants.AGENT_CONTACT_NUMBER_LIST);
            if (CollectionUtils.isNotEmpty(agentContact)) {
                for (String smsNumber : agentContact) {
                    smsUserList.add(smsNumber);
                }
            }
        }
    }

最佳答案

Arrays.asList(testSmsNumber)返回固定大小的列表,因此无法向其添加元素。

更改

smsUserList = Arrays.asList(testSmsNumber);




smsUserList = new ArrayList<>(Arrays.asList(testSmsNumber));


或者,由于您已经使用以下方法创建了ArrayList

List<String> smsUserList = new ArrayList<String>();


更改

smsUserList = Arrays.asList(testSmsNumber);




smsUserList.addAll(Arrays.asList(testSmsNumber));


尽管如果采用第二种方法,则根据您的逻辑,您可能希望在smsUserList.clear()之前调用smsUserList.addAll()(因为代码中有多个位置分配给smsUserList变量,所以也许您希望,则在您每次进行分配时都会清除)。

10-08 17:22