Java中关于枚举的7种用法
生活随笔
收集整理的這篇文章主要介紹了
Java中关于枚举的7种用法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.定義常量:
public enum Color {RED,ORANGE,YELLOW,GREEN,INDIGO,BLUE,PURPLE }2.用于switch:?
enum Color {RED,ORANGE,YELLOW,GREEN,INDIGO,BLUE,PURPLE } public class Draw{Color c = Color.BLUE;public void draw(){switch(c){case RED:c = Color.RED;break;case ORANGE:c = Color.ORANGE;break;case YELLOW:c = Color.YELLOW;break;case GREEN:c = Color.GREEN;break;case INDIGO:c = Color.INDIGO;break;case BLUE:c = Color.BLUE;break;case PURPLE:c = Color.PURPLE;break;}} }?3.在枚舉中添加新方法:
public enum Color {RED(1,"紅"),ORANGE(2,"橙"),YELLOW(3,"黃"),GREEN(4,"綠"),INDIGO(5,"靛"),BLUE(6,"藍(lán)"),PURPLE(7,"紫");//成員變量private int sequence;private String name;//構(gòu)造方法private Color(int sequence, String name) {this.sequence = sequence;this.name = name;}//自定義方法public static String getColorName(int sequence){for (Color c : Color.values()) {if(c.getSequence() == sequence)return c.name;}return null;}//getter&setterpublic int getSequence() {return sequence;}public void setSequence(int sequence) {this.sequence = sequence;}public String getName() {return name;}public void setName(String name) {this.name = name;} }4.覆蓋(重寫)枚舉的方法:
public enum Color {RED(1,"紅"),ORANGE(2,"橙"),YELLOW(3,"黃"),GREEN(4,"綠"),INDIGO(5,"靛"),BLUE(6,"藍(lán)"),PURPLE(7,"紫");//成員變量private int sequence;private String name;//構(gòu)造方法private Color(int sequence, String name) {this.sequence = sequence;this.name = name;}//覆蓋方法 @Overridepublic String toString() {return "順序:"+this.sequence+"_顏色名:"+this.name;} }5.實(shí)現(xiàn)接口:
interface Action{void getDetail(); } public enum Color implements Action{RED(1,"紅"),ORANGE(2,"橙"),YELLOW(3,"黃"),GREEN(4,"綠"),INDIGO(5,"靛"),BLUE(6,"藍(lán)"),PURPLE(7,"紫");//成員變量private int sequence;private String name;//構(gòu)造方法private Color(int sequence, String name) {this.sequence = sequence;this.name = name;}@Overridepublic void getDetail() {System.out.println("順序:"+this.sequence+"_顏色名:"+this.name);} }6.使用接口組織枚舉:
public interface Food { enum Coffee implements Food{ BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO } enum Dessert implements Food{ FRUIT, CAKE, GELATO } }7.枚舉集合:
java.util.EnumSet和java.util.EnumMap是兩個(gè)枚舉集合。EnumSet保證集合中的元素不重復(fù);EnumMap中的key是enum類型,而value則可以是任意類型。
?
轉(zhuǎn)載于:https://www.cnblogs.com/lxcmyf/p/6558514.html
總結(jié)
以上是生活随笔為你收集整理的Java中关于枚举的7种用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 组合破解windows域账号
- 下一篇: 文字两边的横线实现