Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Working with enums

807603Dec 5 2007 — edited Dec 5 2007
I would like to ask the community what is the best practice for converting values into enum types.

for example, let's say I have this enum:
public enum MyEnum {
    TYPE_ONE (1, "One"),
    TYPE_TWO (2, "Two");

    int id;
    String text;

    MyEnum(int id, String text) {
        this.id = id;
        this.text = text;
    }

    public int getID() {
        return id;
    }

    public String getText() {
        return text;
    }
}
Now, is that the best way to make an enum where you want to specify it's ID and be able to retrieve it?

Because what I need to do in code is convert those enum values into the enum type.

Like maybe I parse a string and want to instantiate an enum representing that strings value, like I get a string "One", how to convert it to MyEnum.TYPE_ONE ?

What I do now is:
String testString = "One";
EnumType myType = null;
for (EnumType nextType : EnumType.values()) {
    if (nextType.getText().equals(testString)) {
        myType = nextType;
        break;
    }
}
Is there a better way to do this? Something integrated to the enum framework?

Also, now let's say I save this enum to the database but I save it by it's ID, not it's string value. Then later when I read from the database I want to instantiate the right enum type for the IDs I read, how do I do that? Same thing as above, iterate though all of them and compare the next enum's ID to the one I read from DB?

It seems like there should be an easier (less work on my end) solution.

Please let me know any suggestions you might have, my first time dealing with Java enums.

thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 2 2008
Added on Dec 5 2007
9 comments
621 views