1, 在没有枚举之前, 使用类来定义私有属性那些不被改变的固有的值, 如周一到周日, 而且每次声明都是 public static fianl...
2, 有了枚举后便可以把相关的变量放在一起, 省了每次都用 public static fianl... 声明.
一, 枚举的常用方法
方法 | 说明 |
int compareTo(E o) | 比较此枚举与指定对象的顺序 |
Class<E> getDeclaringClass() | 返回与此枚举常量的枚举类型相对应的 Class 对象 |
String name() | 返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零) |
int ordinal() | 返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零) |
String toString() | 返回枚举常量的名称,它包含在声明中 |
static valueOf(Class | 返回带指定名称的指定枚举类型的枚举常量 |
实验
- public enum Test {
- SUN("周日"),
- MON("周一"),
- TUE("周二"),
- WED("周三"),
- THU("周四"),
- FRI("周五"),
- SAT("周六");
- private Test(String week) {
- }
- public String nextday;
- public String nextday() {
- nextday=Test.THU.toString();
- return nextday;
- }
- }
- public class One1 {
- public static void main(String[] args) {
- //Test d=new Test();
- // 不能创建枚举的对象, 因为枚举的构造方法是 private 修饰
- Test day=Test.MON;
- Test nextday=Test.THU;
- //ordinal() 返回枚举的下标, 注意下标从 0 开始
- System.out.println(day.ordinal());
- // 比较此枚举与指定枚举的顺序, 实则比较它们的下标, 返回一个 int 类型的数字
- System.out.println(day.compareTo(nextday));
- //name() 和 toString() 都是返回字符串形式
- System.out.println(day.name());
- System.out.println(day.toString());
- //
- System.out.println(day.hashCode());
- System.out.println(day.getClass());
- // 遍历枚举
- for(Test i:Test.values()) {
- System.out.println("values"+i);
- }
- System.out.println(isTure(Test.SUN));
- }
- // 比较两者关系是否一样
- static boolean isTure(Test a) {
- if(Test.SUN.equals(a)) {
- return true;
- }
- else {
- return false;
- }
- }
- }
结果:
- 1
- -3
- MON
- MON
- 739498517
- class day14.Test
- values SUN
- values MON
- values TUE
- values WED
- values THU
- values FRI
- values SAT
- true
二, 枚举的一些东西
枚举是一个类, 可以定义属性和方法
由于单继承机制, enum 不能继承其他类, 它已经继承了 java.lang.Enum
枚举里面可以有抽象方法, 也可以实现接口, 不可以被继承的 final 类
第一次写, 看别人写得挺好的, 我还得琢磨,
建议看一下超详细的: https://www.cnblogs.com/alter888/p/9163612.html
------- 来自一名信管人的捡豆子
2019-12-3000:59:46
参考了一下: https://www.cnblogs.com/hyl8218/p/5088287.html
来源: http://www.bubuko.com/infodetail-3357089.html