这种搜索枚举的方式是否可以接受

时间:2016-09-20 17:49:24

标签: java

我正在寻找一种搜索枚举的方法来查看用户提供的字符串是否与任何值匹配,所以我创建了这个。这会被认为是搜索枚举的好方法吗?

enum Month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};

try {
    String A = "DECc";
    Month.valueOf(A);
} catch(Exception e) {
    System.out.println("Could not find an enum with the String you entered");
}

1 个答案:

答案 0 :(得分:0)

是的,这很好..另一种选择是"到字符串"所有枚举元素并逐个比较字符串:

for (Month m : Month.values()) {
    if (m.name().equals(A)) {
        //found
    }
}

但你的方式真的更好......