[英]jre1.6.0_27 HashMap values() sourcecode
今天,我打开了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 }
至少在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 }
您为什么认为这些方法是错误的? 您必须查看HashMap
内部类KeySet
和Values
的源代码才能了解它们的工作原理。
所述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
,在相同的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.