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.
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
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”).
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;    }    ... } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With