Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check valid enum values before using enum

Tags:

java

enums

I'm trying to lookup against an Enum set, knowing that there will often be a non-match which throws an exception: I would like to check the value exists before performing the lookup to avoid the exceptions. My enum looks something like this:

public enum Fruit {     APPLE("apple"),     ORANGE("orange");     ;     private final String fruitname;     Fruit(String fruitname) {         this.fruitname = fruitname;     }     public String fruitname() {return fruitname;} } 

and I want to check if, say, "banana" is one of my enum values before attempting to use the relevant enum. I could iterate through the permissible values comparing my string to

Fruit.values()[i].fruitname 

but I'd like to be able to do something like (pseduo-code):

if (Fruit.values().contains(myStringHere)) {... 

Is that possible? Should I be using something else entirely (Arrays? Maps?)?

EDIT: in the end I've gone with NawaMan's suggestion, but thanks to everyone for all the helpful input.

like image 432
davek Avatar asked Oct 02 '09 13:10

davek


People also ask

Can == be used on enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

How do you use enums correctly?

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).


1 Answers

I really don't know a built-in solution. So you may have to write it yourself as a static method.

public enum Fruit {    ...    static public boolean isMember(String aName) {        Fruit[] aFruits = Fruit.values();        for (Fruit aFruit : aFruits)            if (aFruit.fruitname.equals(aName))                return true;        return false;    }    ... } 
like image 112
NawaMan Avatar answered Sep 25 '22 14:09

NawaMan