Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Enum for keeping Constants [duplicate]

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";
}
like image 294
Hosein Masbough Avatar asked Aug 25 '14 11:08

Hosein Masbough


People also ask

Should I use enum for constants?

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.

Can enum have duplicate values?

CA1069: Enums should not have duplicate values.

Can we have enum containing enum with same constant?

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.

Can we use enum as constants in Java?

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.


2 Answers

It is recommended to use Enum. The possible reasons are like

  • provides default functions to iterate through constants
  • Can write static functions to get the values based on key

It is possible to make the methods by yourself, to make your class self sustained. but the preferable approach is using Enum

like image 91
Vinay Veluri Avatar answered Oct 02 '22 09:10

Vinay Veluri


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.

like image 21
Kao Avatar answered Oct 02 '22 09:10

Kao