枚举类型简介
枚举类型是一种基本数据类型,使用枚举类型,可以取代使用final static定义的常量,即将常量封装在类或者接口中,同时枚举类型还赋予程序在编译时进行检测的功能。放在枚举类型里面的常量是没有具体的值的,定义一个枚举类型使用enum关键字。
package MyPackage_1;public enum Constants {CONSTANTS_A,CONSTANTS_B,CONSTANTS_C,CONSTANTS_D}
当方法以枚举常量作为参数时,只能使用已经定义好的枚举常量,不能使用非枚举常量,这就是枚举类型的检测功能,避免无意义的程序。
枚举类型常用的方法
枚举类型有四个常用的方法:
values():该方法可以将枚举类型的成员以数组形式返回;
valueOf():该方法可以实现将普通字符串转换为枚举类型,但是str的内容一定要和枚举类型的成员一样,否则会抛出异常;
compareTo():该方法用于比较每个枚举对象在定义时的顺序;
ordinal():该方法用于得到枚举成员的位置索引;
package MyPackage_1;public class Test {public static void main(String[] args) {Constants[] array =Constants.values();for(Constants constants:array){System.out.println(constants);System.out.println(constants+"和"+Constants.CONSTANT_B+"的比较结果:"+Constants.CONSTANT_B.compareTo(constants));System.out.println(constants.ordinal());System.out.println("----------------");}System.out.println(Constants.valueOf("CONSTANT_C"));}}
运行结果:
