2012-06-05 87 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

除了上面的回答,哈希表需要的鍵值對。你只是增加了價值而不是關鍵,因此它會拋出異常。