java 无法将散列表添加到集合,singletonmap

jei2mxaa  于 2023-06-04  发布在  Java
关注(0)|答案(3)|浏览(207)
import java.util.*;

public class Hash_Map_Demo {
    public static void main(String[] args) {

        Map<String, String>
                toEmails = Collections
                .singletonMap("key", "Value");

        Map<String, String> userEmails = new HashMap<>();
        userEmails.put("abc@gmail.com", "abc");

        toEmails.putAll(userEmails);

    }
}

当我尝试运行上面的代码时,我遇到了以下异常

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:209)
    at java.util.AbstractMap.putAll(AbstractMap.java:281)
    at Hash_Map_Demo.main(Hash_Map_Demo.java:13)

我明白,在这里我试图添加一个散列表到集合。singletonmap但他们不一样,后面发生了什么。

wgmfuz8q

wgmfuz8q1#

Collections.singletonMap()返回一个不可变的map。使用其他Map实现,例如:

HashMap<String, String> toEmails = new HashMap();
toEmails.put("key", "Value")

Map<String, String> userEmails = new HashMap<>();
userEmails.put("abc@gmail.com", "abc");

toEmails.putAll(userEmails);
ukdjmx9f

ukdjmx9f2#

Collections.singletonMap()返回的map是不可变的,因此在创建后不能修改它:

/**
 * Returns an immutable map, mapping only the specified key to the
 * specified value.  The returned map is serializable.
 *
 * @param <K> the class of the map keys
 * @param <V> the class of the map values
 * @param key the sole key to be stored in the returned map.
 * @param value the value to which the returned map maps {@code key}.
 * @return an immutable map containing only the specified key-value
 *         mapping.
 * @since 1.3
 */
public static <K,V> Map<K,V> singletonMap(K key, V value) {
    return new SingletonMap<>(key, value);
}
xzv2uavs

xzv2uavs3#

Collections.singletonMap()返回SingletonMap。这是Map的实现,但不支持put方法。当调用SingletonMap.putAll时,它会调用SingletonMap.put,然后抛出一个Exception。这就是为什么它是immutable

相关问题