再来谈谈HashMap中的entrySet

HashMap,可能是java中应用较多的Collection之一,之前大概看过一次其中的原理,无非就是先用key的hashcode查找桶,然后用equals比较具体的对象。但是最近在遍历HashMap的时候,发现有个entrySet(),仔细看了源码之后才发现其中的奥秘(当然keySet和ValueSet也是类似的原理,之前还以为keySet是HashMap中的一个副本,囧)

在说EntrySet之前,先看看HashMap的另外一个内部类

private abstract class HashIterator<E> implements Iterator<E> {Entry<K,V> next;// next entry to returnint expectedModCount; // For fast-failint index;// current slotEntry<K,V> current;// current entryHashIterator() {expectedModCount = modCount;if (size > 0) { // advance to first entryEntry[] t = table;while (index < t.length && (next = t[index++]) == null);}}public final boolean hasNext() {return next != null;}final Entry<K,V> nextEntry() {if (modCount != expectedModCount)throw new ConcurrentModificationException();Entry<K,V> 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;}}由于这个方法没有next,所以还是一个抽象类,然后具体用子类实现,比如EntrySet需要用EntryIterator,只要实现next()方法就可以了。对应的KeyIteraror和ValueInteraror也是类似

private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {public Map.Entry<K,V> next() {return nextEntry();}}private final class ValueIterator extends HashIterator<V> {public V next() {return nextEntry().value;}}private final class KeyIterator extends HashIterator<K> {public K next() {return nextEntry().getKey();}}好了,为什么需要用到这些iterator呢? 其实就是后面EntrySet用来的,具体的作用了,就是用iterator来搭起HashMap中具体的entry和entrySet中的桥梁

private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {public Iterator<Map.Entry<K,V>> iterator() {return newEntryIterator();}public boolean contains(Object o) {if (!(o instanceof Map.Entry))return false;Map.Entry<K,V> e = (Map.Entry<K,V>) o;Entry<K,V> candidate = getEntry(e.getKey());return candidate != null && candidate.equals(e);}public boolean remove(Object o) {return removeMapping(o) != null;}public int size() {return size;}public void clear() {HashMap.this.clear();}}这样,对于entrySet的remove方法会体现在HashMap中entry数组(也就是 removeMapping()方法),对entrySet中的clear方法也会影响到HashMap中。(以上情况反之亦然)

注意:1、但是entrySet没有实现add方法,,

2、clear方法中 HashMap.this.clear() 是调用HashMap对象中的clear

版权声明:本文为博主原创文章,未经博主允许不得转载。

己欲立先立人,已欲达先达人。

再来谈谈HashMap中的entrySet

相关文章:

你感兴趣的文章:

标签云: