java枚举之EnumSet and EnumMap

一:EnumSet

import java.util.*;
class EnumSetTest 
{
    //先要有枚举类型
    enum FontConstant{ plain,bold,italic }
    public static void main(String[] args) 
    {
        //调用static函数Enum.of()**
        EnumSet<FontConstant> es = EnumSet.of(FontConstant.plain);//,FontConstant.bold);
        Iterator it = es.iterator();
        while( it.hasNext() )
            System.out.println(it.next());
        System.out.println( EnumSet.complementOf(es) );//static function againg****

        //EnumSet是抽象的,无法实例化
/*        EnumSet<FontConstant> es4 = new EnumSet<FontConstant>(FontConstant.class);
        Iterator it2 = es4.iterator();
        while( it2.hasNext() )
            System.out.println(it2.next());
*/

        //先建立空的枚举set
        EnumSet<FontConstant> es2 = EnumSet.noneOf(FontConstant.class);//static function againg***
        es2.add(FontConstant.plain);//再自己添加
        System.out.println( EnumSet.complementOf(es2) );//输出补集

        ArrayList<FontConstant> al = new ArrayList<FontConstant>();
        al.add(FontConstant.plain);
        al.add(FontConstant.italic);
        //从List里复制内容
        EnumSet<FontConstant> es3 = EnumSet.copyOf(al);//static function againg***
        System.out.println( EnumSet.complementOf(es3) );//static function againg****

    }
}

 

二:EnumMap

package com.shengsiyuan.jdk5;

import java.util.EnumMap;
import java.util.Map;

public class EnumMapDemo
{
	public static void main(String[] args)
	{
		Map<Action, String> map = new EnumMap<Action, String>(Action.class);

		map.put(Action.TURN_RIGHT, "向右转");
		map.put(Action.SHOOT, "射击");
		map.put(Action.TURN_LEFT, "向左转");

		for (Action action : Action.values())
		{
			System.out.println(map.get(action));
		}
	}
}

enum Action
{
	TURN_LEFT, TURN_RIGHT, SHOOT;
}

 

 

你可能感兴趣的:(enumset)