Java 7源码分析第10篇 - Map集合的实现(三)
2014-11-24 07:14:30
·
作者:
·
浏览: 2
ion
vs = values; return (vs != null vs : (values = new Values())); } public Set
> entrySet() { return entrySet0(); } private Set
> entrySet0() { Set
> es = entrySet; return es != null es : (entrySet = new EntrySet()); }
分别得到了KeySet、Values和EntrySet私有类的实例,那么他们是怎么从HashMap中取出这些值的呢?其实这里会涉及到非常多的类和方法,大概框架如下所示:

< http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+yOfJz8Dg1tDX7tbY0qq1xL7NysdIYXNoRW50cnnA4LXEyrXP1qOsyOfPwqO6PC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">private abstract class HashIterator
implements Iterator
{ Entry
next; // next entry to return int expectedModCount; // For fast-fail int index; // current slot Entry
current; // current entry HashIterator() { expectedModCount = modCount; if (size > 0) { // advance to first entry Entry[] t = table; while (index < t.length && (next = t[index++]) == null);// 将index指向第一个table不为null的位置 } } public final boolean hasNext() { return next != null; } final Entry
nextEntry() {// 遍历Entry链 if (modCount != expectedModCount) throw new ConcurrentModificationException(); Entry
e = next; if (e == null) throw new NoSuchElementException(); if ((next = e.next) == null) { Entry[] t = table; while (index < t.length && (next = t[index++]) == null); } current = e; return e; } public void remove() { if (current == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); Object k = current.key; current = null; HashMap.this.removeEntryForKey(k); expectedModCount = modCount; } }
和ArrayList一样,在获取到HashMap的Iterator对象后,就不可以使用ArrayList进行添加或删除的操作了,否则会出现异常。看一下几个重要的变量,如图示。
