如何在java enum中搜索?

use*_*818 1 java enums enumeration constants

我有一些常量,如:

public static final String CONST1="abc";
public static final String CONST2="cde";
public static final String CONST3="ftr";
...................................
public static final String CONSTN="zya";
Run Code Online (Sandbox Code Playgroud)

在一个应用程序中,我需要检查一些值是否在某些常量集中,例如:

if (String val in [CONST1,CONST2,CONST3]) {
do something;}
else {
....
Run Code Online (Sandbox Code Playgroud)

用枚举可以做到这一点吗?或者更好地使用集合或数组?谢谢.

小智 7

你需要的是Enum.valueOf()

返回具有指定名称的指定枚举类型的枚举常量.该名称必须与用于在此类型中声明枚举常量的标识符完全匹配.(不允许使用多余的空白字符.)

下面是我在使用Enums时通常会做的事情的示例,可能会有"坏"数据进入.

public class EnumTest
{
    public static void main(final String[] args)
    {
        final Option o = Option.safeValueOf(args[0]);
        switch(o)
        {
            case CHOICE_A: // fall through
            case CHOICE_B: // fall through
            case CHOICE_C: // fall through
                System.out.format("You selected %s", o );
                break;
            case CHOICE_D:
                System.out.format("You selected %s", o);
                break;
            default:
                System.out.format("Default Choice is %s", o );
        }
    }

    public enum Option
    {
        UNRECOGNIZED_CHOICE, CHOICE_A, CHOICE_B, CHOICE_C;

        // this hides the Exception handling code
        // so you don't litter your code with try/catch blocks
        Option safeValueOf(final String s)
        {
            try
            {
                return Option.valueOf(s);
            }
            catch (final IllegalArgumentException e)
            {
                return UNRECOGNIZED_CHOICE;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以将Array值转换Option.values()为a EnumSet并搜索它们,Exception如果您认为它会获得大量不良数据,则可以避免可能的开销.