枚举类型简介

枚举类型是一种基本数据类型,使用枚举类型,可以取代使用final static定义的常量,即将常量封装在类或者接口中,同时枚举类型还赋予程序在编译时进行检测的功能。放在枚举类型里面的常量是没有具体的值的,定义一个枚举类型使用enum关键字。

  1. package MyPackage_1;
  2. public enum Constants {
  3. CONSTANTS_A,
  4. CONSTANTS_B,
  5. CONSTANTS_C,
  6. CONSTANTS_D
  7. }

当方法以枚举常量作为参数时,只能使用已经定义好的枚举常量,不能使用非枚举常量,这就是枚举类型的检测功能,避免无意义的程序。
image.png

image.png枚举类型常用的方法

枚举类型有四个常用的方法:
values():该方法可以将枚举类型的成员以数组形式返回;
valueOf():该方法可以实现将普通字符串转换为枚举类型,但是str的内容一定要和枚举类型的成员一样,否则会抛出异常;
compareTo():该方法用于比较每个枚举对象在定义时的顺序;
ordinal():该方法用于得到枚举成员的位置索引;

  1. package MyPackage_1;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Constants[] array =Constants.values();
  5. for(Constants constants:array){
  6. System.out.println(constants);
  7. System.out.println(constants+"和"+Constants.CONSTANT_B+"的比较结果:"+Constants.CONSTANT_B.compareTo(constants));
  8. System.out.println(constants.ordinal());
  9. System.out.println("----------------");
  10. }
  11. System.out.println(Constants.valueOf("CONSTANT_C"));
  12. }
  13. }

运行结果:
image.png