enum basics
ä»äºæãJavaã®enumã使ããã¨ãå¤ãã®ã§ããããã¾ãä¸ã®ä¸ã®ããã°ã©ã ã§enumãå ¨åã§ä½¿ã£ã¦ãã¨ããããã¾ãè¦ããã¾ããã
ã¨ãããã¨ã§ãèªåã§ãã©ããªã®ã¨æãã¨ããã¡ãã»ãããenumã®ä½¿ãæ¹ãã¾ã¨ãã¦ã¿ããã¨æãã¾ãããã¨ããããä»åã¯æ®éã®å¾©ç¿ç¨ã«åºæ¬çãªæ©è½ãã
åä»ã®å®æ°ã宣è¨ã§ãã
enumã¯ãã¨ãã¨Cã®intå½¢ã®å¤ã«ååãã¤ããã ããããªãã¦ãåå®å ¨ãªåæå®æ°ãä½ããã£ã¦ãã¨ã§Java5ããå°å ¥ããã¾ããã
ãããªæãã
public enum Sample { HOGE, FOO, BAR, }
ã§ãä¸ã®ä¸ã§è¦ãããenumã¯ä¸è¨ãããã®ã·ã³ãã«ãªã®ãå¤ãã¿ããã§ãã
ã¯ã©ã¹æ¬ä½ã宣è¨ã§ãã
å®æ°å®ç¾©ã®ãã¨ã« ";" ã§åºåãã¨ã以éãã¯ã©ã¹ã®æ¬ä½ã¨ãã¦ã¡ã½ããã¨ãå®ç¾©ã§ãã¾ãã
public enum Sample { HOGE, FOO, BAR, ; // ã»ãã³ãã³ã§åºåã public boolean isHoge() { return this == HOGE; } }
switch-caseãããã
switch-caseã使ãéã«ãã¾ãswitchã®ã»ã¬ã¯ã¿å¼ã®é¨åã«enumåã®å¤ããã®ã¾ã¾çªã£è¾¼ãã¾ããã§ãcaseã©ãã«ã®å¤ã«ã¯å®æ°ã®ååããã®ã¾ã¾æ¸ãã°OKã
Sample s = ...; switch(s) { case HOGE: ... case FOO: ... case BAR: ... }
Comparable, Serializable
ãã®è¾ºãåæã«å®è£
ããã¦ã¾ããã¨ãã«Serializableã¯äººéãæ¸ãã¨å¿ããã¡ãªé¨åã¨ããã¡ããã¨ãã£ã¦ããã¦ããã®ã§ãenumåã§ããã¨ãã¯ããããã»ãããããã¨ã
å¼æ°ã¤ãã®å®æ°ã宣è¨ã§ãã
å®æ°å®£è¨ã®ãã¨ã«()ã§å¼æ°æå®ã§ãã¾ãã1å以ä¸ã®å¼æ°ã使ãå ´åã¯ããã©ã¤ãã¼ãã³ã³ã¹ãã©ã¯ã¿ã®å®£è¨ãå¿ è¦ã
public enum Operator { ADD("+"), SUB("-"), ; private final String symbol; private Operator(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } }
ã¡ãªã¿ã«ãenumã¯ã ããã次ã®ããã«æ¸ãæãããã¾ãã
public class Operator { public static final Operator ADD = new Operator("+"); public static final Operator SUB = new Operator("-"); private final String symbol; private Operator(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } }
ãã ãããã®ã»ãã«ãããããã¨èªåã§ãã£ã¦ãããã®ã§ãä¸ã®ã³ã¼ãæ¸ãããããªãç´ ç´ã«enum使ãã¾ãããã
å®æ°ãã¨ã«å¿åã¯ã©ã¹ãããã¯ãããã
å®æ°ã¯å¼æ°ã®æå®ã ããããªãã¦ãnewã®ã¨ãã¿ããã«å¿åã¯ã©ã¹ãããã¯ãããã¾ãã
enumèªä½ã®ã¯ã©ã¹æ¬ä½ã«abstractã¡ã½ãããæ¸ãã¦ãªã¼ãã¼ã©ã¤ããããã¨ãã§ãã¾ãã
public enum Operator { ADD { @Override public String getSymbol() { return "+"; } }, SUB { @Override public String getSymbol() { return "-"; } }, ; public abstract String getSymbol(); }
ããã¤ããã ããããããªãã¨ãè¡ããã¦ã¾ãã
public abstract class Operator { public static final Operator ADD = new Operator() { @Override public String getSymbol() { return "+"; } }; public static final Operator SUB = new Operator() { @Override public String getSymbol() { return "-"; } }; public abstract String getSymbol(); }
ã¯ã©ã¹ãã¡ã¤ã«è¦ãã¦ã¿ãã¨å¤ãã®ã§ãããæ¬å½ã«ã ããããããªæãã«ãªã£ã¦ãããããADD.getClass()ã¨ãããã¨Operatoråãããªãã¦ãã®ãµãã¯ã©ã¹ãè¿ã£ã¦ãã¾ãã
ãã®ä»£ããã«ãADD.getDeclaringClass()ã£ã¦è¨ãã®ãç¨æããã¦ããã®ã§ããã¡ãã使ã£ãã»ããå®å
¨ã ã¨æãã¾ãã
親ã¤ã³ã¿ã¼ãã§ã¼ã¹ãæå®ã§ãã
æ®éã®ã¯ã©ã¹ã¨åæ§ã«ãimplementsã§è¦ªã¤ã³ã¿ã¼ãã§ã¼ã¹ãããã¾ãã
ãã®è¾ºãããã¾ããªãã¿ããªãããããã¾ããããEffective Javaãªããã§ããã®ãããã®ãã¿ã¼ã³ãããã¤ãç´¹ä»ããã¦ãã¾ããã
public enum Sample implements Runnable { HOGE { public void run() { System.out.println("hogehoge"); } }, FOO { public void run() { System.out.println("fofo"); } }, }
ã§
è¨èªä»æ§ããè¦ãåºæ¬çãªã¨ããã¯ãããªããã ã¨æãã¾ãã復ç¿ã¯ãã®ãããã§ã