gpt4 book ai didi

java - 如何为 Collection 增值

转载 作者:行者123 更新时间:2023-11-29 06:41:46 27 4
gpt4 key购买 nike

我有一个这样的哈希表:

Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("A", "one");
ht.put("B", "two");

然后我调用它的 values() 方法来获取它的值并存储在 像这样的集合对象:

Collection<String> col = ht.values();

现在这个集合对象有这些值:

 one, two.

然后我调用了 col.add("three"); 这次我得到了这个错误:

Exception in thread "main" java.lang.UnsupportedOperationException.

我检查了 API:

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false)

我添加(“三”)到集合的值是唯一的,不是重复的。但是我可以做其他操作,比如 remove()clear() 操作在上面。

无法调用add()。为什么不允许添加?

最佳答案

Hashtable中values()方法返回的集合不支持添加新元素。

来自javadocs :

Returns a Collection view of the values contained in this Hashtable. The Collection is backed by the Hashtable, so changes to the Hashtable are reflected in the Collection, and vice-versa. The Collection supports element removal (which removes the corresponding entry from the Hashtable), but not element addition.

关于java - 如何为 Collection 增值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10892723/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com