Search code examples
javaandroiddesign-patternsenumsstatic-variables

Enum : Difference between using enum and class with static variables


I have a small question with using enum and using a java class and defining static variables.

For example we can define enum like :-

public enum RequestCodeEnum {

    TRANSACTION(1), REPORTS(2), BUDGET(3), CATEGORY(4), CURRENCY(5);

    private int value;

    private RequestCodeEnum(int value) {
        this.value = value;
    }

    public int getCode(){
        return value;
    }

}

And for the same thing, we can use a java class with static variables like :-

public class ActivityRequestCode {

    public static int TRANSACTION_CODE  = 1;
    public static int REPORTS           = 2;
    public static int BUDGET            = 3;
    public static int CATEGORY          = 4;
    public static int CURRENCY          = 5;

}

And for calling both the classes we can do :-

int i = RequestCodeEnum.CATEGORY.getCode();
int j = ActivityRequestCode.TRANSACTION_CODE;

I want to know what difference it will make or are those the alternative solutions to one another. 7

Thank you.


Solution

  • The difference is that the constants are preferred on Android as they consume less memory.

    Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

    See https://developer.android.com/topic/performance/memory.html