重点实验室网站建设,wordpress 主菜单,专业建站方案,朋友圈网站广告怎么做一#xff0c;枚举是什么? 在数学和计算机科学理论中#xff0c;一个集的枚举是列出某些有穷序列集的所有成员的程序#xff0c;或者是一种特定类型对象的计数。这两种类型经常#xff08;但不总是#xff09;重叠。 [1] 是一个被命名的整型常数的集合#xff0c;枚举在…一枚举是什么? 在数学和计算机科学理论中一个集的枚举是列出某些有穷序列集的所有成员的程序或者是一种特定类型对象的计数。这两种类型经常但不总是重叠。 [1] 是一个被命名的整型常数的集合枚举在日常生活中很常见例如表示星期的SUNDAY、MONDAY、TUESDAY、WEDNESDAY、THURSDAY、FRIDAY、SATURDAY就是一个枚举。 ----------参考 baidu.com 讲人话在Java里面就是个继承Object实现Comparable, Serializable接口的类。
二使用的地方
1, 常量的定义2, 可以switch3, 类似类 有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() {// 枚举集合EnumSetMyEnum set EnumSet.noneOf(MyEnum.class);set.add(MyEnum.MON);set.add(MyEnum.FRI);System.out.println(set);}