Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何为集合添加价值_Java - Fatal编程技术网

Java 如何为集合添加价值

Java 如何为集合添加价值,java,Java,我有一个如下的哈希表: Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("A", "one"); ht.put("B", "two"); Collection<String> col = ht.values(); 现在,此集合对象具有以下值: one, two. 然后我叫了col.add(“三”)这一次我得到了这个错误: Exception in thre

我有一个如下的哈希表:

Hashtable<String, String> ht = new Hashtable<String, String>();
 ht.put("A", "one");
 ht.put("B", "two");
Collection<String> col = ht.values();
现在,此集合对象具有以下值:

 one, two.
然后我叫了
col.add(“三”)这一次我得到了这个错误:

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()
。为什么不允许添加?

哈希表中values()方法返回的集合不支持添加新元素

从:

返回此哈希表中包含的值的集合视图。 集合由哈希表支持,因此对哈希表的更改 都反映在集合中,反之亦然。藏品 支持元素删除(从中删除相应的条目) 哈希表),但不是元素添加


哈希表中values()方法返回的集合不支持添加新元素

从:

返回此哈希表中包含的值的集合视图。 集合由哈希表支持,因此对哈希表的更改 都反映在集合中,反之亦然。藏品 支持元素删除(从中删除相应的条目) 哈希表),但不是元素添加


除了上述答案之外,哈希表还需要键值对。您只是在添加值而不是键,因此它会抛出一个异常。

除了上面的答案之外,哈希表还需要键值对。您只是在添加值而不是键,因此它会引发异常