2012-06-05 42 views
1

我有一个哈希表是这样的:如何增加价值到收藏

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

然后我打电话了values()方法来获得它的值,并存储在 Collection对象是这样的:

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) 

,我加入(“三”),以收藏的价值是独一无二的,没有duplicate.But我可以做其他诸如remove()clear()等操作。

无法拨打add()。为什么不允许添加?

回答

7

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.

0

除了上面的回答,哈希表需要的键值对。你只是增加了价值而不是关键,因此它会抛出异常。