枚举 EnumSet类和EnumMap类

EnumSet类

EnumSet底层实现是枚举数组,效率高

  • 枚举是天然线程安全的
public class EnumSetDemo01 {
	public static void main(String[] args) {
//		EnumSet es = EnumSet.noneOf(Weekend.class);
      // EnumSet>枚举的泛型就是枚举  EnumSet的底层是EnumSet> 也就是说EnumSet<这里放的是该类或者是该类的子类>
		EnumSet<Weekend> es = EnumSet.allOf(Weekend.class);//allof补齐Weekend 并排序输出
		System.out.println(es);
		
		/*es.add(Weekend.WEDNESDAY);
		es.add(Weekend.FRIDAY);
		es.add(Weekend.THURSDAY);
		es.add(Weekend.SUNDAY);*/
		
//		System.out.println(es);
	}
}

enum Weekend {
	MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATUARDAY, SUNDAY
}

EnumMap类

public class EnumMapDemo01 {
	public static void main(String[] args) {
		//EnumMap<这里放的是该类或者是该类的子类, V>
        EnumMap<Weekend, String> em = new EnumMap<>(Weekend.class);//
		em.put(Weekend.MONDAY, "星期一");
		em.put(Weekend.THURSDAY, "星期四");
		em.put(Weekend.FRIDAY, "星期五");
		em.put(Weekend.SUNDAY, "星期天");
		em.put(Weekend.WEDNESDAY, "星期三");
		
		System.out.println(em);
		
		for(Weekend w : em.keySet()) {
			String value = em.get(w);
			System.out.println(w.name() + "=" + value);
		}
	}
}
enum Weekend {
	MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATUARDAY, SUNDAY
}

你可能感兴趣的:(枚举 EnumSet类和EnumMap类)