views:

935

answers:

2

Hello,

maybe I am missing something completely. But as far as I understand this, there seems to be no 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 ([http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.html#getKeys[1] =>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/Enuerator" techniques.

Thank you very much Tim

+7  A: 

Apache commons-collections have an adapter that makes the Iterator available for use like an Enumeration. Take a look at IteratorEnumeration.

Adapter to make an Iterator instance appear to be an Enumeration instances

So in short you do the following:

Enumeration enumeration = new IteratorEnumeration(hashMap.keySet().iterator());

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 the Iterator in a constructor, and whenever hasMoreElements() and nextElement() are called, you call the hasNext() and next() on the underlying Iterator.

Use this if you are forced to use Enumeration by some API contract (as I assume the case is). Otherwise use Iterator - it is the recommended option.

Bozho
Google Collections also supports this using `Iterators.asEnumerator()`: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterators.html#asEnumeration(java.util.Iterator)
Joachim Sauer
hello Bozho. Thanks, especially interesting was your comment how to implement this on my own. I did not realize so far that I could do this on my own.
tim
+1 for the lesson.
Adeel Ansari
+5  A: 
sateesh
+1 This is the way to go to as long as you start with the collection. No need to write your own adapter to enumerate a key set.
Samuel Sjöberg