当我在源代码(jdk 1.7(中读取哈希表时。我发现:
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own <tt>remove</tt> operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
* operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
* operations.
*
* @since 1.2
*/
public Set<K> keySet() {
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
你能解释一下我为什么做HashTable.put((,KeySet cahnges吗?
例子 :
Hashtable<String,Integer> hashtable=new Hashtable<>();
hashtable.put("1",1);
hashtable.put("2",1);
hashtable.put("3",1);
Set set= hashtable.keySet();
set.size();
hashtable.put("4",4);
Set set1= hashtable.keySet();
当我调试到'hashtable.put("4",4('时,HashTable 中的键集对象不为空。 我在这里调试:调试图像
当运行"计数++"时,键集将更改。 为什么???
答案在javadoc中:
该集由地图支持,因此对地图的更改将反映在集中,反之亦然。
您的代码会更改地图,对地图所做的更改会反映在集中。
简而言之,键集会更改,因为 javadoc 说它应该更改。
(也许您不明白在这种情况下"反映"是什么意思......