一、枚举的以及使用
Java 枚举是一个特殊的类,一般表示一组常量,比如一年的 4 个季节,一年的 12 个月份,一个星期的 7 天,方向有东南西北等。
Java 枚举类使用 enum 关键字来定义,各个常量使用逗号 , 来分割。
1 2 3 4 5 6 7 8 9 10 11 12 13
| enum Day{ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Day day= Day.MONDAY;
Day day= Day.MONDAY; System.out.println(Day.MONDAY); if(day==Day.MONDAY){ System.out.println("yes"); }
|
枚举类中加入其他常量与方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public enum Day { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7);
Integer integer;
Day(Integer integer) { this.integer = integer; } }
Day day = Day.MONDAY; System.out.println(day.integer); System.out.println(Day.MONDAY.integer);
|
常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13
| Day [] days = Day.values(); System.out.println(Arrays.toString(days));
Day day = Day.MONDAY; System.out.println(day.ordinal());
Day day = Day.valueOf("MONDAY");
|
二、深入理解枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
final class Day extends Enum { public static Day[] values() { return (Day[])$VALUES.clone(); } public static Day valueOf(String s) { return (Day)Enum.valueOf(Day, s); } private Day(String s, int i ) { super(s, i); } public static final Day MONDAY; public static final Day TUESDAY; public static final Day WEDNESDAY; public static final Day THURSDAY; public static final Day FRIDAY; public static final Day SATURDAY; public static final Day SUNDAY; private static final Day $VALUES[];
static { MONDAY = new Day("MONDAY", 0); TUESDAY = new Day("TUESDAY", 1); WEDNESDAY = new Day("WEDNESDAY", 2); THURSDAY = new Day("THURSDAY", 3); FRIDAY = new Day("FRIDAY", 4); SATURDAY = new Day("SATURDAY", 5); SUNDAY = new Day("SUNDAY", 6); $VALUES = (new Day[] { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }); } }
|