为什么' keySet'哈希表更改时更改?

时间:2018-01-02 02:58:57

标签: java hashtable keyset

当我在源代码中读取Hashtable时(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();

当我调试到&#39; hashtable.put(&#34; 4&#34;,4)&#39;时,HashTable中的keyset对象不为null。我在这里调试: debuging img

运行&#39; count ++&#39;。键集将改变。为什么???

1 个答案:

答案 0 :(得分:0)

答案在javadoc中:

  

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

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

简而言之,密钥集会更改,因为javadoc表示应该更改。

(也许你不明白&#34;反映&#34;在这种情况下是 ...)