In my situation, given an enum, check if that enum belongs to a specific list of enums or not.
My solution is putting all of the enums that I want to compare to the given enum to an ArrayList. So I can use contains(..) method of the ArrayList to do the checking task.
PokemonEnums givenPokemon = ...;
ArrayList<PokemonEnums> AshPokemonList = ...;
while(doing something){
if(AshPokemonList.contains(givenPokemon){
//do fun stuffs
}
}
Is it acceptable in term of performance or is there any other way I can do this in a more elegant way?
P/S: Although I know that AshPokemonList will probably not contain more 10, I can use if with multiple checks, but then it looks quite messy to me. But I don't know in term of performance, will it be better?
Java provides a special container called EnumSet<T> which is optimized for working with enums:
PokemonEnums givenPokemon = ...;
EnumSet<PokemonEnums> ashPokemonSet = ...;
while(doing something){
if(ashPokemonSet.contains(givenPokemon) {
//do fun stuffs
}
}
This implementation should be better than an array list, because it employs bit vectors internally:
Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."
No, it is not "acceptable", because this has linear complexity, so the run time depends on the length of the list.
Use an EnumSet instead. This class is not sorted, but you can check in constant time whether an enum is contained, no matter how big the set is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With