枚举的使用

package com.roykw.enumsingleton;

/**
 * 最典型的枚举使用
 * @author zhangwei
 */
public enum ColorSelector {
	RED,BLUE,GREEN;
	
	public ColorSelector get(){
		return this;
	}
	public static void main(String[] args) {
		ColorSelector blue = ColorSelector.BLUE;
		switch(blue){
		case RED:
			System.out.println("red color");
			break;
		case BLUE:
			//通过ordinal()方法获得元素的位置
			System.out.println("blue color and the index is " + ColorSelector.BLUE.ordinal());
			break;
		default:
			System.out.println("green color");
			break;
		}
		
		//比较元素的值
		System.out.println(ColorSelector.RED.compareTo(ColorSelector.BLUE));
		
		System.out.println(ColorSelector.RED.get());
		
	}
}

package com.roykw.enumsingleton;

/**
 * 枚举构造方法的使用
 * @author zhangwei
 *
 */
public enum EnumConstructor {
	min(20),mid(25),max(30),mix(20,"good"){
		
		public int getValue() {
			return 5;
		}
	};
	
	private int value;
	private String level;
	
	EnumConstructor(int value){
		this.value = value;
	}
	
	EnumConstructor(int value,String level){
		this.value = value;
		this.level = level;
	}

	
	public int getValue() {
		return value;
	}
	
	public String getLevel(){
		return level;
	}
	
	public static void main(String[] args) {
		//EnumConstructor.values()获得枚举类的所有值
		System.out.println("min: "+EnumConstructor.values()[0].getValue());
		
		System.out.println("level: "+EnumConstructor.values()[3].getLevel());//good
		System.out.println("level: "+EnumConstructor.values()[3].getValue());//5,可见值被修改了
	}
}

package com.roykw.enumsingleton;

/**
 * 带有抽象方法的枚举的使用
 * @author zhangwei
 */
public enum EnumAbstract {
	XIAOMING {
		@Override
		public String getName() {
			return "I am XiaoMing";
		}
	};
	
	public abstract String getName();
	
	public static void main(String[] args) {
		System.out.println(EnumAbstract.XIAOMING.getName());
	}
}


你可能感兴趣的:(String)