2011-10-31 51 views
1

我已經設置的常量,如:如何在java枚舉中搜索?

public static final String CONST1="abc"; 
public static final String CONST2="cde"; 
public static final String CONST3="ftr"; 
................................... 
public static final String CONSTN="zya"; 

在應用程序中,我需要檢查,如果某個值在某些組常量,如:

if (String val in [CONST1,CONST2,CONST3]) { 
do something;} 
else { 
.... 

是否有可能有這樣做枚舉?還是更好地使用一個集合或一個數組? 謝謝。

回答

6

你需要的是Enum.valueOf()

返回指定枚舉類型與 指定名稱的枚舉常量。該名稱必須完全匹配用於在此類型中聲明枚舉常量的標識符 。 (多餘的空格 字符是不允許的。)

這裏是我通常用枚舉工作,並有可能當一個例子「壞」數據的到來。

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; 
      } 
     } 
    } 
} 

,你也可以轉換將Array的值從Option.values()轉換爲EnumSet,然後搜索它們並避免可能的Exception的開銷,如果您認爲它會收到大量不良數據。

+0

好的迴應。涵蓋了各個方面,寫得很好。 – RockyMM

4

您可以使用枚舉在switch語句@Dims建議:

switch (val) { 
    case CONST1: case CONST2: case CONST3: 
     do_something(); 
    break; 
    case CONST4: 
     do_something_else(); 
    break; 
    default: 
     // we should not be here?!? 
    break; 
} 

,我認爲val是一個枚舉。你可以將其創建爲@賈羅德 - 羅伯遜建議:

val = MyEnum.valueOf(stringValue);   
+1

如果'stringValue'不會是枚舉值之一,那麼一定要在try-catch中包裝'valueOf()'。另外請注意,如果這種情況發生了很多,您將花費構建Exception對象並通過try-catch機制的一小部分時間。 – dtyler

2

退房java.util.EnumSet中 - 這是枚舉優化的一組特殊的實現。