I'm not sure if HashMap or TreeMap store Map.Entry in itself. That is, it's likely to return Map.Entry instance created on the fly when entrySet().iterator().next() is called.
Personally, I think it may be better in this form:
class Entry {
Object key;
Object value;
}
interface InplaceIterator {
boolean next();
}
Entry entryBuf = new Entry();
InplaceIterator it = map.entrySet().inplaceIterator(entryBuf);
while (it.next()) {
// do with entryBuf...
}
Thus, the creation of Entry is avoided.
I don't know how Java Compiler works, will Java Compiler optimize the creation of Map.Entry away, by analyzing the dataflow and get the knowledge that Map.Entry can be safely reused?
Or, is someone there have already written another collection framework to enable inplace iteration?