0

今日、jre1.6.0_27 HashMap values() メソッドのソースコードを開きました

  389  public Set<K> keySet()
  390  {
  391      Set localSet = this.keySet;
  392      return (this.keySet = new KeySet(null));
  393  }
  394
  395  public Collection<V> values()
  396  {
  397      Collection localCollection = this.values;
  398      return (this.values = new Values(null));
  399  }

これらのソースコードはエラーだと思いますが、なぜこのようになっているのかわかりません。誰が理由を教えてくれますか?

=======================================

皆さんありがとうございます。これはEclipseの問題だと思います。このソースコードはEclipse F3を使用して行ったので、上記のようになります。

src.zip を開くだけで、このメソッドのソースコードは正しいです。

/**
 * Returns a {@link Collection} view of the values contained in this map.
 * The collection is backed by the map, so changes to the map are
 * reflected in the collection, and vice-versa.  If the map is
 * modified while an iteration over the collection is in progress
 * (except through the iterator's own <tt>remove</tt> operation),
 * the results of the iteration are undefined.  The collection
 * supports element removal, which removes the corresponding
 * mapping from the map, via the <tt>Iterator.remove</tt>,
 * <tt>Collection.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.
 */
903    public Collection<V> values() {
904        Collection<V> vs = values;
905        return (vs != null ? vs : (values = new Values()));
906    }
4

2 に答える 2

0

なぜこれらの方法が間違っていると思いますか? これらがどのように機能するかを理解するには、内部クラスKeySetValues内部のソース コードを確認する必要があります。HashMap

keySet()メソッドは新しいオブジェクトを返しますKeySet。JDK 1.6.0_35 では、内部クラスのソース コードはKeySet次のようになります。

private final class KeySet extends AbstractSet<K> {
    public Iterator<K> iterator() {
        return newKeyIterator();
    }
    public int size() {
        return size;
    }
    public boolean contains(Object o) {
        return containsKey(o);
    }
    public boolean remove(Object o) {
        return HashMap.this.removeEntryForKey(o) != null;
    }
    public void clear() {
        HashMap.this.clear();
    }
}

Setからデータを取得する の実装ですHashMap

Values同様に、同じように機能する内部クラスがあります。

于 2012-09-28T09:51:36.000 に答える
0

少なくとも OpenJDK 7 では正しいように見えます。

  880       public Set<K> keySet() {
  881           Set<K> ks = keySet;
  882           return (ks != null ? ks : (keySet = new KeySet()));
  883       }

  916       public Collection<V> values() {
  917           Collection<V> vs = values;
  918           return (vs != null ? vs : (values = new Values()));
  919       }
于 2012-09-28T09:40:37.893 に答える