LoginSignup
14

More than 5 years have passed since last update.

EnumMapの使い方メモ

Last updated at Posted at 2014-06-03

EnumMapの使い方メモです。

名前と値を対応付けるのにわかりやすそうです。

Month.java
package enum_test;

import java.util.EnumMap;

public enum Month {
    JANUARY, FEBRUARY, MARCH, APRIL,
    MAY, JUNE, JULY, AUGUST,
    SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;

    private final static EnumMap<Month, Integer> monthMap;

    static{
        monthMap = new EnumMap<Month, Integer>(Month.class);
        monthMap.put(Month.JANUARY, 1);
        monthMap.put(Month.FEBRUARY, 2);
        monthMap.put(Month.MARCH, 3);
        monthMap.put(Month.APRIL, 4);
        monthMap.put(Month.MAY, 5);
        monthMap.put(Month.JUNE, 6);
        monthMap.put(Month.JULY, 7);
        monthMap.put(Month.AUGUST, 8);
        monthMap.put(Month.SEPTEMBER, 9);
        monthMap.put(Month.OCTOBER, 10);
        monthMap.put(Month.NOVEMBER, 11);
        monthMap.put(Month.DECEMBER, 12);
    }

//    public int toInteger(){
//        return monthMap.get(this);
//    }

    public static int toInteger(Month month){
        return monthMap.get(month);
    }

//    public static Month fromInteger(int value){
//        for(Month month: Month.values()){
//            if(monthMap.get(month) == value){
//                return month;
//            }
//        }
//        throw new IllegalArgumentException(); //範囲外。
//    }
}

逆変換は使うことはないでしょうという想定。
おまけで作った余計なコードはコメントアウトしておきます(^^;

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
14