アットウィキロゴ

enum

TypeSafeEnum

余り特筆することはないが
定義
enum TestEnum{
  FOO,BAR,BAR
}
使い方
public static void main(String args[]){
  TestEnum e = TestEnum.FOO;
  System.out.println(e.name());    ←"FOO"とでる
  System.out.println(e.ordinal()); ←"0"とでる

  TestEnum e2 = TestEnum.valueOf("FOO");
  System.out.println(e2.name());    ←"FOO"とでる
  System.out.println(e2.ordinal()); ←"0"とでる

  for(TestEnum e3 : TestEnum.values()){
    System.out.println(e3.name());    ←"FOO","BAR","BAZ"とでる
     System.out.println(e3.ordinal()); ←"0","1","2"とでる
  }

  switch(e3){
    case TestEnum.FOO :
      ...
      break;
    case TestEnum.BAR :
      ...
      break;
    case TestEnum.BAZ :
      ...
      break;
    default :
      ...
      break;
  }
} 
カスタマイズ
  • カスタムメソッド定義可能。それぞれオーバライドもできるが使わないだろう。使いそうなのはstaticメソッドかな?
enum SwitchCaseEnum{
  ONE,TWO,THREE;
  public static SwitchCaseEnum next(SwitchCaseEnum current){
  switch(e3){
    case SwitchCaseEnum.ONE:
      return SwitchCaseEnum.TWO;
    case SwitchCaseEnum.TWO:
      return SwitchCaseEnum.THREE;
    case SwitchCaseEnum.THREE:
      throw new RuntimeException();
    default :
      throw new RuntimeException();
  }
}
  • 属性はこんな感じ
enum AttributeEnum{
  ONE(1),TWO(2),THREE(3);
  private int number;
  private AttributeEnum(int number){
    this.number = number;
  }
}

タグ:

+ タグ編集
  • タグ:
最終更新:2008年10月05日 18:11
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。