39
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Java] enumをswitch文で分岐させる

Posted at

はじめに

enum型の変数をswitch文で分岐させたい時にハマったのでメモ。

やろうとしたこと

こんな感じのenumがあって渡されたenum型の値をswitch文で分岐させようとした。

HogeType.java
public enum HogeType {
  NONE(0),
  FIRST(1),
  SECOND(2)
}

ダメな例

public void hoge(HogeType hogeType){
  switch(hogeType){
    case HogeType.FIRST:
      System.out.println("first");
      break;
    case HogeType.SECOND:
      System.out.println("second");
      break;
    default:
      System.out.println("none");
  }
}

この中のcase HogeType.FIRST:の部分でエラーが出ていました。内容はan enum switch case label must be the unqualified name of an enumeration constantというものです。

正解

public void hoge(HogeType hogeType){
  switch(hogeType){
    case FIRST:
      System.out.println("first");
      break;
    case SECOND:
      System.out.println("second");
      break;
    default:
      System.out.println("none");
  }
}

調べたところenum型をswitch文の引数にとる場合は、caseに与える値を定数にしなければならないらしいです。つまりHogeType.という記述がいらなくなります。

39
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?