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.

6
  • 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 Commented Dec 5, 2016 at 8:07
  • @T.J. I think it's probably a dup somewhere but the marked one is too general for this instance. Commented Dec 5, 2016 at 8:08
  • @ChiefTwoPencils: Perhaps: stackoverflow.com/questions/5252465/… Commented Dec 5, 2016 at 8:10
  • 1
    Please check out this video youtube.com/watch?v=Hzs6OBcvNQE and use @IntDef or equivalent -> developer.android.com/reference/android/support/annotation/… Commented Dec 5, 2016 at 8:12
  • @T.J. I like it better because it's android specific. Commented Dec 5, 2016 at 8:13

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would also read this answer: stackoverflow.com/questions/29183904/…
Thank you both for the answer. Now I have a clear idea about when to use enums.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.