创建带值枚举

自定义枚举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 }

 

转载于:https://www.cnblogs.com/echo1314/p/10312679.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值