Java 1.5 enums are a life saver. There is a small gotcha in thier use especially in a switch statement(More so for a guy coming from hard core 1.4).
When creating an enum reference - you would need to Qualify with enum Type. However, The case labels while switch(ing) on an enum variable will only take enum constant of the *SAME* enum type. And ONLY the constant name. It SHOULD not be QUALIFIED.
Ex: In the following code, The second case label gives a compilation error.
There are good advantages here. For one, Refactoring doesnot involve lot of changes. Maintains Typesafety. It avoids a possibility of human error where you are comparing Fruit enums and Vegitable enums. Because they are different :)
When creating an enum reference - you would need to Qualify with enum Type. However, The case labels while switch(ing) on an enum variable will only take enum constant of the *SAME* enum type. And ONLY the constant name. It SHOULD not be QUALIFIED.
Ex: In the following code, The second case label gives a compilation error.
public class EnumTest {
enum WeekDays {SUN, MON, TUE, WED, THU, FRI, SAT};
public static void main(String arg[]) {
WeekDays r = WeekDays.SUN;
switch (r) {
case SUN:
break;
case WeekDays.MON:
break;
default:
break;
}
}
}There are good advantages here. For one, Refactoring doesnot involve lot of changes. Maintains Typesafety. It avoids a possibility of human error where you are comparing Fruit enums and Vegitable enums. Because they are different :)