java Enum示例

package com.xx.tests;



import java.util.HashMap;

import java.util.Map;



public enum Season {

	Spring {

		@Override

		public String toString() {

			return "春天";

		}

	},

	Summer{

		@Override

		public String toString() {

			return "夏天";

		}

	},

	Autumn{

		@Override

		public String toString() {

			return "秋天";

		}

	},

	Winter{

		@Override

		public String toString() {

			return "冬天";

		}

	};

	

	private static final Map<Integer,Season> lookup=new HashMap<Integer,Season>();

	static{

		for (Season se : Season.values()) {

			lookup.put(se.ordinal(), se);

		}

	}

	

	public static Season fromOrdinal(int idx){

		return lookup.get(idx);

	}

}

  

 

package com.xx.tests;



import java.util.EnumSet;



import org.junit.Test;



public class TestSeason {



	@Test

	public void test() {

		Season sea = Season.Spring;

		System.out.println(sea);

		

		for (Season s : Season.values()) {

			System.out.println(s);

			System.out.println( s.ordinal());

		}

		System.out.println("########");

		Season s1 = Enum.valueOf(Season.class, "Spring");

		System.out.println(s1);

		System.out.println("########");

		System.out.println(Season.fromOrdinal(3));

		

		System.out.println("########");

		EnumSet<Season> es = EnumSet.allOf(Season.class);

		for (Season season : es) {

			System.out.println(season);

		}

		System.out.println("########");

		EnumSet<Season> es2= EnumSet.of(Season.Autumn, Season.Winter);

		for (Season season : es2) {

			System.out.println(season);

		}

	}



}

  

 

你可能感兴趣的:(java)