关于EnumMap、EnumSet的使用

enum定义是别人的,第一次看见这种用法,就测试了一下。发现EnumMap的使用与网上大家写的不一样呢,哪位大侠知道:

public enum WeekDayOfEnum{
Mon("Monday"), Tue("Tuesday"), Wed("Wednesday"), Thu("Thursday"), Fri( 
    "Friday"), Sat("Saturday"), Sun("Sunday"); 

/* 定义枚举自己的属性 */
private final String day;

// 通过括号给枚举值赋值,就必须有带参构造器和一属性跟方法
private WeekDayOfEnum(String day){
this.day = day;
}

/* 定义枚举自己的方法*/
public static void printDay(int i){
switch(i){
case 1: System.out.println(WeekDayOfEnum.Mon);break;
case 2: System.out.println(WeekDayOfEnum.Tue);break;
case 3: System.out.println(WeekDayOfEnum.Wed);break;
case 4: System.out.println(WeekDayOfEnum.Thu);break;
case 5: System.out.println(WeekDayOfEnum.Fri);break;
case 6: System.out.println(WeekDayOfEnum.Sat);break;
case 7: System.out.println(WeekDayOfEnum.Sun);break;

default:System.out.println("Wrong Number");
}
}

public String getDay(){
return day;
}
}


测试代码:
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;

public class EnumTest {

public void testWeekDayOfEnum(){
for(WeekDayOfEnum day : WeekDayOfEnum.values())
System.out.println(day + " : " + day.getDay());
WeekDayOfEnum.printDay(1);
}

public void printEnum(){
for(WeekDayOfEnum days : WeekDayOfEnum.values()){
System.out.println(days.name() + " " + days.getDay());
}
}

public void testWeekDayOfEnumByMap(){
EnumMap<WeekDayOfEnum,String> day = new EnumMap<WeekDayOfEnum, String>(WeekDayOfEnum.class);
day.put(WeekDayOfEnum.Mon,"星期一");
day.put(WeekDayOfEnum.Sat,"星期六");
for(Map.Entry<WeekDayOfEnum, String> entry : day.entrySet()){
String tmp = entry.getKey().getDay();
System.out.println(tmp);
}

/*
Iterator<Map.Entry<WeekDayOfEnum,String>> it = day.entrySet().iterator();
while(it.hasNext()){
Map.Entry<WeekDayOfEnum,String> entry = it.next(); 
System.out.println(entry.getKey().getDay());
}
*/
}

public void testWeekDayOfEnumBySet(){
EnumSet<WeekDayOfEnum> set = EnumSet.allOf(WeekDayOfEnum.class);
for(WeekDayOfEnum days : set)
System.out.println(days.getDay());
}

public static void main(String[] args){
EnumTest et = new EnumTest();
//et.testWeekDayOfEnum();
//et.testWeekDayOfEnumBySet();
//et.printEnum();
et.testWeekDayOfEnumByMap();
}
}

没搞懂,为啥“day.put(WeekDayOfEnum.Mon,"星期一");”这句并没有改变WeekDayOfEnum.Mon的属性值,费解!

你可能感兴趣的:(关于EnumMap、EnumSet的使用)