问题
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.
回答1:
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.
回答2:
I think you can use the method enumeration from java.util.Collections class to achieve what you want.
The API doc of the method enumerate has this to say:
public static Enumeration enumeration(Collection c)
Returns an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.
For example, the below code snippet gets an instance of Enumeration from the keyset of HashMap
final Map <String,Integer> test = new HashMap<String,Integer>();
test.put("one",1);
test.put("two",2);
test.put("three",3);
final Enumeration<String> strEnum = Collections.enumeration(test.keySet());
while(strEnum.hasMoreElements()) {
System.out.println(strEnum.nextElement());
}
and resulting the output is:
one
two
three
回答3:
You can write a adapter to adapt to Enumeration.
public class MyEnumeration implements Enumeration {
private Iterator iterator;
public MyEnumeration(Iterator iterator){
this.iterator = iterator;
}
public MyEnumeration(Map map) {
iterator = map.keySet().iterator();
}
@Override
public boolean hasMoreElements() {
return iterator.hasNext();
}
@Override
public Object nextElement() {
return iterator.next();
}
}
And then you can use this custom enumeration :)
来源:https://stackoverflow.com/questions/2048131/get-an-enumeration-for-the-keys-of-a-map-hashmap-in-java