As far as I understand this, it seems that there is not a direct way of getting an Enumeration directly for the Keys of a HashMap. I can only get a keySet(). From that Set, I can get an Iterator but an Iterator seems to be something different than an Enumeration.
What is the best and most performant way to directly get an Enumeration from the Keys of a HashMap?
Background: I am implementing my own ResourceBundle (=>getKeys() Method), and I have to provide/implement a method that returns the Enumeration of all Keys. But my implementation is based on a HashMap so I need to somehow figure out how to best convert betweens these two “Iterator/Enumerator” techniques.
Apache commons-collections have an adapter that makes the
Iteratoravailable for use like anEnumeration. Take a look at IteratorEnumeration.So in short you do the following:
Alternatively, if you (for some reason) don’t want to include commons-collections, you can implement this adapter yourself. It is easy – just make an implementation of
Enumeration, pass theIteratorin a constructor, and wheneverhasMoreElements()andnextElement()are called, you call thehasNext()andnext()on the underlyingIterator.Use this if you are forced to use
Enumerationby some API contract (as I assume the case is). Otherwise useIterator– it is the recommended option.