Java 无法将元素添加到映射-不支持的操作异常

Java 无法将元素添加到映射-不支持的操作异常,java,android,kotlin,Java,Android,Kotlin,我在这个可变映射中插入元素时遇到了困难,我不知道为什么? 我可以看到它返回了Map,所以它不应该成为一个问题来放入元素。 你能帮我吗 myClient.authentications.put(“基本身份验证”,httpBasicAuth) 身份验证如下所示: public Map<String, Authentication> getAuthentications() { return authentications; } 当前,默认情况下,此字段具有null值,因

我在这个可变映射中插入元素时遇到了困难,我不知道为什么? 我可以看到它返回了Map,所以它不应该成为一个问题来放入元素。 你能帮我吗

myClient.authentications.put(“基本身份验证”,httpBasicAuth)

身份验证如下所示:

public Map<String, Authentication> getAuthentications() {
        return authentications;
}

当前,默认情况下,此字段具有
null
值,因此您不能对其调用任何方法。所以当你打电话时:

myClient.authentications.put("basicAuthentication", httpBasicAuth)
您正在尝试在
null
上调用方法
put()

要解决此问题,您可以从以下位置更改初始化:
私有地图认证;
至(在Java中):

private Map authentications=new HashMap();
或在to中(在Kotlin中):

private val身份验证:Map=mapOf();

在这些更改之后,此字段将被初始化为
空数组
,而不是
null
。请记住,当您有一些基于它的逻辑时(例如,您正在检查
身份验证==null
),此更改非常重要。

现在,您的代码不会显示您如何初始化
身份验证。你的价值从何而来?好吧,我又添加了一些代码。您能再检查一下吗?我仍然看不到您在哪里为
身份验证赋值。非常感谢。那句话节省了我一些时间。我使用的是一个外部库,看起来它们是一个不可修改的映射。@IVELINIEV我的解决方案有效吗?
目前,默认情况下,此字段有空值,因此您不能向其中添加任何值我不确定你在这里得到了什么。这里的问题是一个不可修改的映射,与空值无关。身份验证库中通常使用不可修改的映射或集合。
public class HttpBasicAuth implements Authentication {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
        if (username == null && password == null) {
            return;
        }
        headerParams.put("Authorization", Credentials.basic(
            username == null ? "" : username,
            password == null ? "" : password));
    }

 val httpBasicAuth = HttpBasicAuth()
                httpBasicAuth.username = "user"
                httpBasicAuth.password = "pass"
                myClient.authentications.put("basicAuthentication", httpBasicAuth)
myClient.authentications.put("basicAuthentication", httpBasicAuth)
private Map<String, Authentication> authentications;
private Map<String, String> authentications = new HashMap<>();
private val authentications: Map<String, Authentication> = mapOf();