枚举类型

枚举类型

最近在程序里用到了枚举类型处理异常的返回值,和异常code挺方便,推荐大家使用枚举类型

enum  Other {
ONE,TWO,TREE_BOOK
}

由于枚举类型的实例是常量,因此按照命名惯例他们都用大写表示,如果在一个名字中有多个单词,用下划线将它们隔开。

public class EurekaApplication {

   public static void main(String[] args) {
      SpringApplication.run(EurekaApplication.class, args);
      Other other = Other.TREE_BOOK;
      System.out.println(other);
   }

}
enum  Other {
ONE,TWO,TREE_BOOK
}

在你创建enum时,编译器会自动添加一些有用的特性,例如,它会创建toString()方法,以便你可以很方便的显示某个enum的实例(相当于对象,不是成员变量)的名字,ordinal()方法用来表示某个特定enum常量的声明顺序,以及static value()方法,用来按照enum常量的声明顺序,产生由这些常量构成的数组。

public class EurekaApplication {

   public static void main(String[] args) {
      SpringApplication.run(EurekaApplication.class, args);
      for(Other s:Other.values()){
         System.out.println(s+"顺序号"+s.ordinal());
      }
   }

}
enum  Other {
ONE,TWO,TREE_BOOK
}

可以将enum当做其他任何类来处理,事实上,enum确实是类,并且具有自己的方法。

public class EurekaApplication {

   public static void main(String[] args) {
      SpringApplication.run(EurekaApplication.class, args);
      Other other = Other.ONE;
      switch (other){
         case ONE:
            System.out.println("1");
            break;
         case TWO:
            System.out.println("2");
            break;
         case TREE_BOOK:
            System.out.println("3");
            break;
            default:
               System.out.println("输入不正确");
      }
   }

}
enum  Other {
ONE,TWO,TREE_BOOK
}

其实default 有没有都行,要是输入值不对,编译器不通过

由于switch是要在有限的可能值集合中进行选择,因此它与enum正式绝佳的组合。

enum  Coffeesize3 {
   BIG(8),HIGE(10),OVERWHELMING(16);
   Coffeesize3(int ounces) {
      this.ounces = ounces;
   }
   private  int ounces;

}

枚举类型可以有构造器,其中的8.10,16是构造器参数,不是顺序号

public class EurekaApplication {
   Coffeesize3 size;
   public static void main(String[] args) {
      SpringApplication.run(EurekaApplication.class, args);
      EurekaApplication drink = new EurekaApplication();
      drink.size = Coffeesize3.BIG;
      System.out.println(drink+", ounces:"+drink.size.getOunces());
      }
}
enum  Coffeesize3 {
   BIG(8),HIGE(10),OVERWHELMING(16);
   Coffeesize3(int ounces) {
      this.ounces = ounces;
   }
   private  int ounces;
   public int getOunces(){
      return ounces;
   }

}

输出


猜你喜欢

转载自blog.csdn.net/fwk19840301/article/details/79369617