java枚举enum实用小技巧!不看后悔!!
前言
早就知道枚举了,可却一直不知道合理去应用,今天发现一个小例子,才发现枚举真香!
enum应用
public enum CountryEnum {
ONE(1,"齐"),TWO(2,"楚"),THREE(3,"燕"),FOUR(4,"赵"),FIVE(5,"魏"),SIX(6,"韩");
private Integer retCode;
private String retMessage;
CountryEnum(Integer retCode, String retMessage) {
this.retCode = retCode;
this.retMessage = retMessage;
}
public Integer getRetCode() {
return retCode;
}
public String getRetMessage() {
return retMessage;
}
public static CountryEnum forEach_CountryEnum(int index){
//代表每个枚举对象ONE TWO
CountryEnum[] myArray = CountryEnum.values();
for(CountryEnum ele:myArray){
if(index == ele.getRetCode()){
return ele;
}
}
return null;
}
}
test
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for(int i = 1;i <=6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "\t 国灭亡");
countDownLatch.countDown();
},CountryEnum.forEach_CountryEnum(i).getRetMessage()).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "====秦统一");
}
-----------------
楚 国灭亡
齐 国灭亡
燕 国灭亡
赵 国灭亡
魏 国灭亡
韩 国灭亡
main====秦统一