enum的使用

1、枚举的定义
可以根据实际需要在构造器中设置多个参数。

public enum Color {
	RED("red", "红色"),
	BULE("blue", "蓝色"),
	YELLOW("yellow", "黄色");
	
	private String type;
	private String msg;
	
	Color(String type,String msg) {
		this.type = type;
		this.msg = msg;
	}
//省略get和set方法
}

2、枚举的使用

Color[] values = Color.values();
for (int i = 0; i < values.length; i++) {
	System.out.println(values[i].getType() + "-----" + values[i].getMsg());
}

输出信息:

red-----红色
blue-----蓝色
yellow-----黄色

3、EnumSet和EnumMap

EnumSet<Color> enumSet = EnumSet.allOf(Color.class);
enumSet.add(Color.BULE);
enumSet.add(Color.RED);
enumSet.add(Color.YELLOW);
enumSet.add(Color.BULE);
for (Color color : enumSet) {
	System.out.print(color.getType() + "\t");
}


EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class); 
enumMap.put(Color.RED, "红色");
enumMap.put(Color.YELLOW, "黄色");
enumMap.put(Color.BULE, "蓝色");
System.out.println(enumMap);

输出信息:

red	blue	yellow	
{RED=红色, BULE=蓝色, YELLOW=黄色}

可以看出EnumSet中存储的是唯一不重复的信息。

4、在switch-case语句中使用枚举

/**
 * @Location com.giser
 * @Notes {颜色}
 * @author giserDev
 * @Date 2019-05-11 12:06:35
 */
public enum Color {
	
	RED(1, "red", "红色"),
	BLACK(2, "black", "黑色"),
	YELLOW(3, "yellow", "黄色"),
	BLUE(4, "blue", "蓝色"),
	WHITE(5, "white", "白色");
	
	private Integer index;
	private String value;
	private String msg;
	
	private Color(Integer index, String value, String msg) {
		this.index = index;
		this.value = value;
		this.msg = msg;
	}
	
	/**
	 * @Notes {根据index获取对应颜色值,返回枚举类型}
	 * @author giserDev
	 * @Date 2019-05-11 12:08:34
	 */
	public static Color getValue(Integer index) {
		Color[] colors = Color.values();
		for (Color color : colors) {
			if(color.index == index) {
				return color;
			}
		}
		return null;
	}

    //省略getters和setters
	
	public static void main(String[] args) {
		System.out.println(Color.getValue(3));
		
		Random random = new Random();
		int index = random.nextInt(Color.values().length) + 1;//[1,6)
		while(true) {
			System.out.println(index);
			switch(Color.getValue(index)) {
				case RED:
					System.out.println(RED.msg);
					break;
				case BLACK:
					System.out.println(BLACK.msg);
					break;
				case YELLOW:
					System.out.println(YELLOW.msg);
					break;
				case BLUE:
					System.out.println(BLUE.msg);
					break;
				case WHITE:
					System.out.println(WHITE.msg);
					break;
				default:
					break;
			}
			index = random.nextInt(5) + 1;
		}
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值