`keyset`的使用和实现

keyset的使用和实现

keyset可以获取Map中所有的key值,查看keyset方法。

KeySet是HashMap的内部类,在keyset方法中返回KeySet实例,没有添加key元素;

public Set<K> keySet() {
    Set<K> ks = keySet;
    if (ks == null) {
        ks = new KeySet();
        keySet = ks;
    }
    return ks;
}

final class KeySet extends AbstractSet<K> {
    public final int size()                 { return size; }
    public final void clear()               { HashMap.this.clear(); }
    public final Iterator<K> iterator()     { return new KeyIterator(); }
    public final boolean contains(Object o) { return containsKey(o); }
    public final boolean remove(Object key) {
        return removeNode(hash(key), key, null, false, true) != null;
    }
    public final Spliterator<K> spliterator() {
        return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
    }
    public final void forEach(Consumer<? super K> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }
}

通过编译keyset的使用方法,查看keyset的本质;

public class MapTest {
    public static void main(String[] args)
    {
        Map<String, String> map = new HashMap<String, String>();

        map.put("1","uranus");
        map.put("2", "leon");

        Set<String> ks = map.keySet();

        for (String s : ks)
        {
            System.out.println(s);
        }
    }
}

使用jad编译上述代码,jad .\MapTest.class。从编译后代码可以看出,keyset的使用是通过iterator获取所有键值。

public class MapTest
{

    public MapTest()
    {
    }

    public static void main(String args[])
    {
        Map map = new HashMap();
        map.put("1", "uranus");
        map.put("2", "leon");
        Set ks = map.keySet();
        String s;
        for(Iterator iterator = ks.iterator(); iterator.hasNext(); System.out.println(s))
            s = (String)iterator.next();
    }
}

查看类KeySet中的迭代器,返回外部类HashMap中的KeyIterator类。

public final Iterator<K> iterator()     { return new KeyIterator(); }

查看KeyIterator类,继承了HashIterator类。

final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

查看HashIterator

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);
        }
    }

    public final boolean hasNext() {
        return next != 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;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        expectedModCount = modCount;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,839评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,259评论 19 139
  • 集合框架: 1)特点:存储对象;长度可变;存储对象的类型可不同2)Collection(1)List:有序的;元素...
    Demo_Yang阅读 1,320评论 0 4
  • 松月洞童话村位于仁川港区,与仁川艺术平台、自由广场、中华街连结成观光区块景点,是相当成功的小区改造范例,整个街区充...
    美舒阅读 1,164评论 8 2
  • 学校有很多丁香,每到春天的时候,漂亮的丁香争相开放,白色的,紫色的,香味飘扬在整个学校。 虽然已经立春,但是天气依...
    渠六亿阅读 272评论 0 4