【问题标题】:Getting java.lang.UnsupportedOperationException in List [duplicate]在列表中获取 java.lang.UnsupportedOperationException [重复]
【发布时间】:2019-01-02 04:28:21
【问题描述】:

我得到了

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);
                }
            }
        }
    }

【问题讨论】:

  • 请问,您是从哪一行得到这个的。?

标签: java


【解决方案1】:

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.addAll() 之前调用smsUserList.clear()(因为您的代码中有多个位置分配给smsUserList 变量,所以也许您想要List 每次分配时都会被清除)。

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 2017-09-29
    • 2019-10-24
    • 2013-06-07
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2021-10-31
    • 2016-07-29
    相关资源
    最近更新 更多