-4

当我在源代码(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++”时。键集会改变。为什么???

4

1 回答 1

0

答案在 javadoc 中:

集合由地图支持,因此对地图的更改会反映在集合中,反之亦然。

您的代码会更改地图,而对地图的更改会反映在集合中。

简而言之,键集更改是因为 javadoc 说它应该更改。

(也许你不明白在这种情况下“反射”是什么意思......)

于 2018-01-02T03:09:28.200 回答