栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Map的keySet()和entrySet()的性能注意事项

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Map的keySet()和entrySet()的性能注意事项

首先,这完全取决于您使用的地图类型。但是,由于JavaRanch线程讨论了HashMap,因此我假设这就是您所指的实现。并假设您正在谈论Sun /
Oracle的标准API实现。

其次,如果您在遍历哈希映射时担心性能,我建议您看一下

linkedHashMap
。从文档:

在linkedHashMap的集合视图上进行迭代需要的时间与地图的大小成正比,而不管其容量如何。
在HashMap上进行迭代可能会更昂贵,需要的时间与其容量成正比。

HashMap.entrySet()

此实现的源代码可用。实现基本上只是返回一个new

HashMap.EntrySet
。一个看起来像这样的类:

private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {    public Iterator<Map.Entry<K,V>> iterator() {        return newEntryIterator(); // returns a HashIterator...    }    // ...}

HashIterator
看起来像

private abstract class HashIterator<E> implements Iterator<E> {    Entry<K,V> next;    // next entry to return    int expectedModCount;   // For fast-fail    int index;      // current slot    Entry<K,V> current; // current entry    HashIterator() {        expectedModCount = modCount;        if (size > 0) { // advance to first entry Entry[] t = table; while (index < t.length && (next = t[index++]) == 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;    }    // ...}

这样就可以了…那就是指示您遍历entrySet时将发生什么的代码。它遍历整个数组,该数组与地图的容量一样长。

HashMap.keySet()和.get()

在这里,您首先需要掌握这组键。这花费的时间与地图的 容量 成正比(而不是linkedHashMap的 大小
)。完成此操作后,您需要

get()
为每个键调用一次。当然,在一般情况下,具有良好的hashCode实现会花费固定的时间。但是,这不可避免地需要大量的
.hashCode
.equals
呼叫,这显然要比仅进行
entry.value()
呼叫花费更多的时间。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485693.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号