0
1

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.

Enum逆引きマップ Java

Last updated at Posted at 2019-01-09

Enumの値からEnum自身を逆引きしたい用途があったので備忘録として残します。

String値を値にもつEnumでの実装例

public enum Mode {
   MODEA("a"),
   MODEB("b");

   private String mode;

   private Mode(String mode) {
       this.mode = mode;
   }

   /** 逆引きマップをあらかじめ作成してフィールドで持っとく */
   private static final Map<String, Mode> modeMap = new HashMap<String, Mode>() {
      private static final long serialVersionUID = 1L;
      {
           for (Mode mode : Mode.values()) {
               put(mode.mode, mode);
           }
       }
   };

   /** 値からEnumを取得 */
   public static Mode getMode(String mode) {
       return modeMap.get(mode);
   }
} 

利用側

Mode modeA = Mode.getMode("a");

逆引きマップをあらかじめ作っておいてStringをキーにEnumを取得できる。
マップなのでダイレクトアクセスできて処理効率が良さげ。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?