124

I am almost done with a calculation activity I am working with in android for my app. I try to create a Gender Enum, but for some reason getting Syntax error, insert "EnumBody" to complete EnumDeclaration.

public static enum Gender
{
    static
    {
        Female = new Gender("Female", 1);
        Gender[] arrayOfGender = new Gender[2];
        arrayOfGender[0] = Male;
        arrayOfGender[1] = Female;
        ENUM$VALUES = arrayOfGender;
    }
}

I have also tried it without the static {} but I get the same syntax error.

4
  • Enums are not recommended for performance issues, use primitive constants instead. youtube.com/watch?v=Hzs6OBcvNQE
    – Myke Dev
    Commented Oct 16, 2015 at 19:43
  • 2
    UPDATE 2019: Enums are fine to use in Android since ART replaced DALVIK as runtime environment stackoverflow.com/a/56296746/4213436. Therefore I think most answers on this thread are irrelevant.
    – JDenais
    Commented Sep 20, 2019 at 8:20
  • @JDenais of course you mean the thread 'you' just referenced
    – YoussefDir
    Commented Apr 9, 2020 at 17:31
  • @YoussefDir 🐟 Enjoy your meal! Commented Apr 3 at 12:30

6 Answers 6

372

Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.

public enum Gender {
   MALE,
   FEMALE
}

If you want them to be more complex, you can add values to them like this.

public enum Gender {
    MALE("Male", 0),
    FEMALE("Female", 1);

    private String stringValue;
    private int intValue;
    private Gender(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

Then to use the enum, you would do something like this:

Gender me = Gender.MALE
10
  • 16
    I will give that a try, I did say I was an absolute beginner
    – JMSDEV
    Commented Feb 12, 2012 at 7:02
  • 93
    Sorry, I didn't mean that negatively. Just the weirdest syntax I've ever seen for an Enum
    – Spidy
    Commented Feb 12, 2012 at 7:15
  • 4
    Its also helpful to mention enums are sequential so you can use .ordinal() on the enum to get the int value.
    – Kalel Wade
    Commented Apr 25, 2014 at 20:24
  • 1
    The syntax in the question is the kind one might come up with from using a decompiler.
    – Dan Getz
    Commented Jun 8, 2016 at 20:26
  • 12
    I laughed so much on "Where on earth did you find this syntax" . Saying just like a teacher to his student Commented Aug 10, 2016 at 7:34
50

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

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

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

5
  • 2
    There has been some places - could you add some if you know them? because I can't find any Commented Apr 22, 2015 at 15:07
  • 10
    Here somebody noticed that information about using ints instead of enums was removed from Performance Tips in official documentation. Moreover, I've made research and posted summary on reddit Commented Apr 23, 2015 at 8:34
  • 1
    Android Performance Patterns: The price of ENUMs (100 Days of Google Dev) Commented Nov 4, 2015 at 6:56
  • 1
    Guys, my question is if Enum is "bad" practice, why does Google still support this feature of Java with Android? :( Commented Nov 6, 2015 at 23:01
  • 5
    @JesúsCastro Because Google wants to ensure that companies with lots of existing Java business logic (which may be using enums) can just drop their library into an Android project and go. Commented Jan 28, 2016 at 16:36
25

As commented by Chris, enums require much more memory on Android that adds up as they keep being used everywhere. You should try IntDef or StringDef instead, which use annotations so that the compiler validates passed values.

public abstract class ActionBar {
...
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
@Retention(RetentionPolicy.SOURCE)
public @interface NavigationMode {}

public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;

@NavigationMode
public abstract int getNavigationMode();

public abstract void setNavigationMode(@NavigationMode int mode);

It can also be used as flags, allowing for binary composition (OR / AND operations).

EDIT: It seems that transforming enums into ints is one of the default optimizations in Proguard.

1
18
public enum Gender {
    MALE,
    FEMALE
}
0
10

According to this Video if you use the ProGuard you don't need even think about Enums performance issues!!

Proguard can in many situations optimize Enums to INT values on your behalf so really don't need to think about it or do any work.

5

Android's preferred approach is int constants enforced with @IntDef:

public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;

@Retention(RetentionPolicy.SOURCE)
@IntDef ({GENDER_MALE, GENDER_FEMALE})
public @interface Gender{}

// Example usage...
void exampleFunc(@Gender int gender) {
  switch(gender) {
  case GENDER_MALE:

     break;
  case GENDER_FEMALE:
     // TODO
     break;
  }
}

Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.