I know the usage of enum in java.
Is recommended to use enums for storing the program constants(rather than the class described below)?
public class Constants{
public static final String DB_CF_NAME = "agent";
public static final String DB_CF_ID = "agent_id";
public static final String DB_CF_TEXT = "agent_text";
public static final String DB_CF_LATITUDE = "latitude";
}
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
CA1069: Enums should not have duplicate values.
The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc. All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.
A Java Enum is a Java type-class used to define collections of constants for your software according to your own needs. Each item in a Java enum is called a constant, an immutable variable — a value that cannot be changed.
It is recommended to use Enum. The possible reasons are like
It is possible to make the methods by yourself, to make your class self sustained. but the preferable approach is using Enum
Yes, you're right - it is recommended to use enums for storing the program constants.
As you can see on examples below, this approach allows you to:
add/override useful methods for your string literals:
public enum Days {
MONDAY("Monday"),
TUESDAY("Tuesday"),
SUNDAY ("Sunday");
private final String name;
private Day(String s) {
name = s;
}
use built-in methods for Enums
:
public boolean equalsName(String otherName){
return (otherName == null)? false : name.equals(otherName);
}
use EnumMap
and EnumSet
:
private EnumSet<Option> badDays = EnumSet.of(Days.MONDAY, Days.TUESDAY);
Here is a good discussion about this.
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