Contents
When should I use enums?
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
What is the point of enum?
The entire point of enums are to make your code more readable. They are not casted to ints, since they are by default ints. The only difference is instead of going back and forth checking what int values you may have, you can have a clear set of enums to make the code more readable.
Is EnumMap thread safe?
Java EnumMap is not thread-safe. You can make thread-safe by doing Collections.
Can a male enum be converted to a female enum?
We should never assume that one enum identically relates to another – especially when we may not have control over one or another. This is a little better, as MyGender.Male will still convert to TheirGender.Male even if the integer representation is changed, but still not ideal.
Is it bad to assume one enum equates to another?
Also, it is generally bad to assume that one enum equates to another by name, as this might not be the case in some contexts. As mentioned earlier, an ideal approach would work for other enum-mapping requirements. This approach explictly maps MyGender to TheirGender using a switch statement.
Can a integer be held in an enum?
An enum can hold any value between its smallest and largest values, so what you have is mainly correct. The only thing you need to do additionally is to make sure the integer argument is in the proper range, since if you try to cast an int that is outside the range of the enumeration, you have undefined behavior:
When to change the name of an enum?
Covers the case where the underlying integer value changes. Covers the case where the enum names changes (i.e. no assumptions – the developer will need to update the code to handle the scenario – good). Handles cases where enum values cannot be mapped.