Enum列挙応用説明


列挙の応用は主にenumタイプに対して、カスタムの属性を追加して、構造の方法を増加して、カスタムの方法(抽象の方法)を増加して、カスタムの属性に対してメンテナンスして便利です
詳細は、コード例3を参照してください.
1、カスタム列挙、列挙原理を分析する
2、列挙enumを使用して、一般的な方法を表示する
3、列挙応用例
4、列挙は一例を迅速に実現する一つの方法とすることができる
1、
/**
 *       
 *         ,           、    、         
 * 
 *                   ,                  ,
 *                      ,       
 * 
 */
public abstract class WeekDay1 {

/**
 *          
 * 1、       
 * 2、                    
 * 3、              ,  :   nextDay        。
 *         nextDay      if else            
 *  
 *          ,              
 */
	private WeekDay1() {
	}

	public final static WeekDay1 SUN = new WeekDay1(){
		@Override
		public WeekDay1 nextDay() {
			return MON;
		}
		
	};
	public final static WeekDay1 MON = new WeekDay1(){
		@Override
		public WeekDay1 nextDay() {
			return SUN;
		}
		
	};

	
	//nextDay  ,        ,
	public abstract WeekDay1 nextDay();
	
/*	public WeekDay nextDay() {
		if (this == SUN) {
			return MON;
		}
		if (this == MON) {
			return SUN;
		}
		return null;
	}
*/
	public String toString() {
		return this == SUN?"SUN":"MON";
	}
}

2、
public class EnumTest {	
	public static void main(String[] args) {
				
		WeekDay weekDay1=WeekDay.MON;
		System.out.println(weekDay1);

		WeekDay weekDay2=WeekDay.SAT;
		/*System.out.println(weekDay2);
		System.out.println(weekDay2.name());
		System.out.println(weekDay2.ordinal());//        
		
		//          
		System.out.println(WeekDay.valueOf("SUN"));
		
		//     ,    
		System.out.println(Arrays.toString(WeekDay.values()));
*/
	}
	
	public enum WeekDay{
		SUN(4),MON,TUE,WES,THI,FRI,SAT;
	
		private WeekDay(){
			System.out.println("frist");
		};
		private WeekDay(int day){
			System.out.println("second");
		};
	}
	
	public enum TrafficLamp{
		RED(10) {
			public TrafficLamp nextLamp() {
				return TrafficLamp.GREEN;
			}
		},
		GREEN(20) {
			public TrafficLamp nextLamp() {
				return TrafficLamp.YELLOW;
			}
		},
		YELLOW(30) {
			public TrafficLamp nextLamp() {
				return TrafficLamp.RED;
			}
		};
		
		private int time;
		
		public abstract TrafficLamp nextLamp();			

		private TrafficLamp(int time){
			this.time=time;
		}
	}
}

3、
/**    :        */
public enum ResultEnum {

	/**  */
	SUCCESS(0,"  "),
	/**  */
	ERROR(1,"  ");
	
	// ...
	//              
	
	private  Integer code;
	private String msg;
	
	ResultEnum(Integer code,String msg){
		this.code=code;
		this.msg=msg;
	}
	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
}