创建带值枚举

自定义枚举1:

 1 package com.echo.springboot.constants;
 2 
 3 public enum AppConstants {
 4 
 5     COUNT_EVERYPAGE(8),
 6     CODE_SUCCESS(1),
 7     CODE_FAIL(0);
 8 
 9     private final int value;
10 
11     private AppConstants(int value){
12         this.value=value;
13     }
14     public int getValue(){
15         return value;
16     }
17 }

 

注意构造函数是必须的并且是私有的,还有其中的value是必须的。上面是自定义的。

自定义枚举2:

 1 package com;
 2  
 3 public enum Color {
 4      
 5      RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
 6      
 7      
 8     private String name ;
 9     private int index ;
10      
11     private Color( String name , int index ){
12         this.name = name ;
13         this.index = index ;
14     }
15      
16     public String getName() {
17         return name;
18     }
19     public void setName(String name) {
20         this.name = name;
21     }
22     public int getIndex() {
23         return index;
24     }
25     public void setIndex(int index) {
26         this.index = index;
27     }
28      
29  
30 }
 1 package com;
 2  
 3 public class B {
 4  
 5     public static void main(String[] args) {
 6  
 7         //输出某一枚举的值
 8         System.out.println( Color.RED.getName() );
 9         System.out.println( Color.RED.getIndex() );
10  
11         //遍历所有的枚举
12         for( Color color : Color.values()){
13             System.out.println( color + "  name: " + color.getName() + "  index: " + color.getIndex() );
14         }
15     }
16  
17 }

 

posted @ 2019-01-24 09:24  echo314  阅读(434)  评论(0编辑  收藏  举报