简体   繁体   English

如何检查Java枚举中的值?

[英]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: 我试图弄清楚如何在Java中使用枚举,但我不知道如何做到这一点:

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". 因此,我将传递“ Oink”并返回PIG,但是如果传递“ Chirp”,则会出现某种错误,因为“ 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() ; 对于其中的一些,遍历values() for many, create a Map<String, AnimalSounds> , as suggested here . 对于许多Map<String, AnimalSounds> ,请按照此处的建议创建一个Map<String, AnimalSounds>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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