简体   繁体   中英

How can I check for a value in a Java Enumeration?

I'm trying to figure out how to use enumerations in Java, and I don't get how to do this:

public enum animalSounds {
    CAT("meow"),
    DOG("Woof"),
    PIG("Oink"),

    public final String animalName;

    animalSounds(String noise) {
        this.animalName = noise
    }

}

What I'm trying to do, is pass in a string, and see if that string exists in the set of enumerables. So, I would pass in "Oink" and get back PIG, but if I pass in "Chirp", I would get some sort of error, as there is not enumeration value with "Chirp".

enum is not the best thing to do for what you are trying to do but you could try

private animalSounds getAnimal(String noise) {
    for(animalSounds a : animalSounds.values())
    {
        if(a.animalName.equals(noise))
        {
            return a;
        }
    }
    throw new IllegalArgumentException();
}

使用values()方法-遍历不同类型,执行逻辑。

For a few, iterate through the values() ; for many, create a Map<String, AnimalSounds> , as suggested here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM