Working with Enums in android

JMSDEV picture JMSDEV · Feb 12, 2012 · Viewed 150.5k times · Source

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.

Answer

Spidy picture Spidy · Feb 12, 2012

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