4

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.

viper
  • 1,836
  • 4
  • 25
  • 41
  • 2
    If you want a generic answer check the answers of the other question, but If you want an answer specific to android, please rewrite your question to clearly mention it – Nicolas Filotto Dec 05 '16 at 08:07
  • @T.J. I think it's probably a dup somewhere but the marked one is too general for this instance. – ChiefTwoPencils Dec 05 '16 at 08:08
  • @ChiefTwoPencils: Perhaps: http://stackoverflow.com/questions/5252465/android-enum-vs-static-final-ints – T.J. Crowder Dec 05 '16 at 08:10
  • 1
    Please check out this video https://www.youtube.com/watch?v=Hzs6OBcvNQE and use @IntDef or equivalent -> https://developer.android.com/reference/android/support/annotation/IntDef.html – StefMa Dec 05 '16 at 08:12
  • @T.J. I like it better because it's android specific. – ChiefTwoPencils Dec 05 '16 at 08:13
  • I am not talking specifically about any programming language. Just the code design pattern – viper Dec 05 '16 at 09:17

1 Answers1

5

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

barq
  • 3,681
  • 4
  • 26
  • 39
  • 2
    I would also read this answer: http://stackoverflow.com/questions/29183904/should-i-strictly-avoid-using-enums-on-android – abbath Dec 05 '16 at 08:06
  • Thank you both for the answer. Now I have a clear idea about when to use `enums`. – viper Dec 05 '16 at 09:25