mireazma
mireazma

Reputation: 556

What's the type of *the* element in a Set?

I have this code:

for(GlCapabs_e capName : capabs.keySet()){
    x = capName.get();
}

where GlCapabs_e is an enum and capabs is an EnumMap<GlCapabs_e, Boolean>. But GlCapabs_e type up there is wrong, as I can't use get() on capName; it can't be a constant, it has to be a type to support get() so to return the value of the key.

I've read somewhere in Java documentation (I can't find it anymore) that a "special" type exists like elementOf, itemOf or something alike but googling them didn't return anything pertaining my matter. And above this I'm not sure whether it's this type that I'm supposed to use.

Upvotes: 0

Views: 49

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280132

You're iterating over the keySet. If you want to get the value mapped to each key in the key set, use the EnumMap to retrieve the value

for(GlCapabs_e capName : capabs.keySet()){
    x = capabs.get(capName);
}

Or iterate over the entrySet

for (Entry<GlCapabs_e, Boolean> entry : capabs.entrySet()) {
    x = entry.getValue(); // the entry holds both the key and the mapped value
}

Remember, EnumMap is an implementation of Map, it therefore inherits/implements all of its methods.

Upvotes: 1

Related Questions