有没有一种方法可以遍历 EnumMap 而不会导致每次迭代都创建新的对象?条目集的迭代器每次都返回一个新条目。我能看到的唯一方法是
for(K k: map.keySet())
foo(k, map.get(k));
为了澄清这一点,具体是关于 EnumMap ,它在其 EntrySet 上具有以下迭代器实现
public Map.Entry<K,V> next() {
if (!hasNext())
throw new NoSuchElementException();
lastReturnedEntry = new Entry(index++);
return lastReturnedEntry;
}