简体   繁体   中英

How to compare an input string with an enum?

I have my below enum -

public enum TestEnum {
    h1, h2, h3, h4;

    public static String forCode(int code) {
    return (code >= 0 && code < values().length) ? values()[code].name() : null;
    }

    public static void main(String[] args) {
        System.out.println(TestEnum.h1.name());
        String ss = "h1";

        // check here whether ss is in my enum or not

    }
}

Now what I want to check is given a String h1 , I need to see whether this String h1 is in my enum or not? How would I do this using the enum?

You should avoid using ordinals for your enum . Rather give a value to each enum constant, and have a field.

So, your enum should look like:

public enum TestEnum {
    h1("h1"), h2("h2"), h3("h3"), h4("h4");

    private final String value;

    TestEnum(String value) { this.value = value; }

    public static TestEnum forValue(String value) {
        // You can cache the array returned by `values()` in the enum itself
        // Or build a map from `String` to `TestEnum` and use that here
        for (TestEnum val: values()) {
            if (val.value.equals(value)) {
                return val;
            }
        }
    }
}

And then for a given String, you can check if it's valid value or not like this:

String value = "h1";

TestEnum enumValue = TestEnum.forValue(value);

if (enumValue == null) {
    System.out.println("Invalid value");
}

Easiest approach:

try {
   TestEnum.valueOf(ss); 
   System.out.println("valid");
} catch (IllegalArgumentException e) {
   System.out.println("invalid");
}

Setting values for each enum seemed unnecessary to me. Here's a solution that uses toString() instead of .value, which I feel is a bit simpler:

public class tester {

public static void main(String[] args) {

    TestEnum enumValue = TestEnum.forValue("X1");
    if (enumValue == null) {
        System.out.println("Invalid value");
    } else {
        System.out.println("Good  value");
    }
}

public enum TestEnum {
    X1, X2, X#;

    public static TestEnum forValue(String value) {
        for (TestEnum val : values())
            if (val.toString().equals(value))
                return val;
        return null;
    }
}

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