当我在源代码(jdk 1.7)中阅读 Hashtable 时。我发现:
/**
* 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 中的键集对象不为空。我在这里调试: 调试img
运行“count++”时。键集会改变。为什么???