一,枚举是什么?
在数学和计算机科学理论中,一个集的枚举是列出某些有穷序列集的所有成员的程序,或者是一种特定类型对象的计数。这两种类型经常(但不总是)重叠。 [1] 是一个被命名的整型常数的集合,枚举在日常生活中很常见,例如表示星期的SUNDAY、MONDAY、TUESDAY、WEDNESDAY、THURSDAY、FRIDAY、SATURDAY就是一个枚举。
----------参考 baidu.com
讲人话,在Java里面就是个继承Object实现Comparable, Serializable接口的类。
二,使用的地方
- 1, 常量的定义
- 2, 可以switch
- 3, 类似类 有set, get 构造(private EnumName(){…}), 有普通方法, 有静态
- 4, 可以实现接口
- 5, 接口组织枚举
- 6, 枚举集合
三,代码实现
- 常量与接口
public interface MyEnumInterface {void print();
}
定义常量并实现接口
public enum MyEnum implements MyEnumInterface {// 常量定义SUN, MON, TUE, WED, THT, FRI, SAT;@Overridepublic void print() {System.out.println(SUN + "...");}// 得到常量static void constant() {MyEnum sun = MyEnum.SUN;System.out.println(sun + "==>" + MyEnum.valueOf("SUN"));}// switch 与枚举使用static void swithEnum(MyEnum me) { switch(me) {case SUN:System.out.println("sunday!");break;case MON:break;case TUE:break;case WED:break;case THT:break;case FRI:break;case SAT:break;default:break;}}}
- 枚举类似类的用法,有构造,字段,函数,多了常量。
enum Color {// 向枚举添加方法BLUE("蓝色", 0), ORANGE("橙色", 1), YELLOW("黄色", 2);// 这个变量得用上,否则报错private String name;private int index;// 枚举里面的构造方法没得class修饰了private Color(String name, int index) {this.name = name;this.index = index;}// 遍历常量 得到颜色public static String getName(int index) {for(Color color: Color.values()) {if (index == color.getIndex()) {return color.getName();}}return null;}// set getpublic String getName() {return name;}public void setName(String name) {this.name = name;}public int getIndex() {return index;}public void setIndex(int index) {this.index = index;}// 重写toString() 方法public String toString() {return getName() + ":" + getIndex();}}
- 取枚举的值
static void testColor() {String name = Color.getName(0);System.out.println(name);Color blue = Color.BLUE;// 常量 BLUESystem.out.println(blue);// 常量名称 BLUESystem.out.println(blue.name());System.out.println("重写了toString后, 返回下标枚举值 " + blue.toString());}
- 组织枚举接口
public interface MyEnumInterface {void print();
}// 发现了一个小秘密,接口里面可以有方法体,用枚举...
interface Food {// 组织枚举接口 在接口里面实现接口的枚举enum Meat implements Food {SHEEP_MEAT, FISH_MEAT, BACON_MEAT;void eat(Meat me) {if (me.equals(SHEEP_MEAT)) {System.out.println("SHEEP_MEAT!");}}}}
- 枚举集合
static void testEnumList() {// 枚举集合EnumSet<MyEnum> set = EnumSet.noneOf(MyEnum.class);set.add(MyEnum.MON);set.add(MyEnum.FRI);System.out.println(set);}