首页 > 代码库 > Map的entrySet()方法

Map的entrySet()方法

当调用hashmap的entrySet()时,得到是一个EntrySet内部类的对象。

Set<Map.Entry<K,V>>  entryset;
EntrySet时AbstractSet类的子类,实现了set的接口,所以能够引用给entryset
    public Set<Map.Entry<K,V>> entrySet() {        Set<Map.Entry<K,V>> es;        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;    }

当我们调用上面得到的对象的方法时,如staff.entrySet().iterator().next(),此时返回外部类的一个对象,这个类继承了HashIterator,此时调用的是这个迭代器中的next,此时执行HashIterator中的nextNode,nextNode返回table中的下一个。得到是一个EntrySet内部类的对象。

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }        public final void clear()               { HashMap.this.clear(); }        public final Iterator<Map.Entry<K,V>> iterator() {            return new EntryIterator();        }        public final boolean contains(Object o) {            if (!(o instanceof Map.Entry))                return false;            Map.Entry<?,?> e = (Map.Entry<?,?>) o;            Object key = e.getKey();            Node<K,V> candidate = getNode(hash(key), key);            return candidate != null && candidate.equals(e);        }        public final boolean remove(Object o) {            if (o instanceof Map.Entry) {                Map.Entry<?,?> e = (Map.Entry<?,?>) o;                Object key = e.getKey();                Object value = http://www.mamicode.com/e.getValue();>

 

final class EntryIterator extends HashIterator        implements Iterator<Map.Entry<K,V>> {        public final Map.Entry<K,V> next() { return nextNode(); }    }

  

      abstract class HashIterator {      Node<K,V> next; // next entry to return      Node<K,V> current; // current entry      int expectedModCount; // for fast-fail      int index; // current slot      HashIterator() {      expectedModCount = modCount;      Node<K,V>[] t = table;      current = next = null;      index = 0;      if (t != null && size > 0) { // advance to first entry      do {} while (index < t.length && (next = t[index++]) == null);      }    }     final Node<K,V> nextNode() {            Node<K,V>[] t;            Node<K,V> e = next;            if (modCount != expectedModCount)                throw new ConcurrentModificationException();            if (e == null)                throw new NoSuchElementException();            if ((next = (current = e).next) == null && (t = table) != null) {                do {} while (index < t.length && (next = t[index++]) == null);            }            return e;        }    }

 

  

Map的entrySet()方法