如何在集合中增加价值

UVM*_*UVM 1 java

我有一个像这样的Hashtable:

Hashtable<String, String> ht = new Hashtable<String, String>();
 ht.put("A", "one");
 ht.put("B", "two");
Run Code Online (Sandbox Code Playgroud)

然后我调用它的values()方法来获取它的值并存储在Collection对象中,如下所示:

Collection<String> col = ht.values();
Run Code Online (Sandbox Code Playgroud)

现在这个集合对象具有以下值:

 one, two.
Run Code Online (Sandbox Code Playgroud)

然后我打电话col.add(" three");这次我收到了这个错误:

Exception in thread "main" java.lang.UnsupportedOperationException.
Run Code Online (Sandbox Code Playgroud)

我检查了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)
Run Code Online (Sandbox Code Playgroud)

我添加("三")到集合的值是唯一的,而不是重复.但我可以执行其他操作,如操作remove()clear()操作.

无法打电话.add()为什么不允许添加?

Rah*_*hul 7

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

来自javadocs:

返回此Hashtable中包含的值的Collection视图.Collection由Hashtable支持,因此对Hashtable的更改将反映在Collection中,反之亦然.Collection支持元素删除(从Hashtable中删除相应的条目),但不支持元素添加.