首先,这完全取决于您使用的地图类型。但是,由于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()呼叫花费更多的时间。



