public enum DayOfWeek {This simple program:
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class DayOfWeekTest {Will return:
public static void main(String[] args) {
DayOfWeek dow = DayOfWeek.MONDAY;
System.out.println(dow.toString());
}
}
$ java DayOfWeekTestBut in the program above what I really want is an abbreviated version of the week day in Title Case; For example Mon. Now I could override the toString method of the enum class as follows:
MONDAY
public enum DayOfWeek {Which does meet my needs, but it’s not the most obvious or readable piece of code. What Java allows you to do is provide a constructor for the enumeration as follows:
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public String toString() {
String dayOfWeek = name().toString();
dayOfWeek = dayOfWeek.charAt(0) + dayOfWeek.substring(1,3).toLowerCase();
return dayOfWeek;
}
}
public enum DayOfWeek {Which I think we can all agree is a far simpler piece of code.
MONDAY("Mon"), TUESDAY("Tue"), WEDNESDAY("Wed"), THURSDAY("Thu"), FRIDAY("Fri"), SATURDAY("Sat"), SUNDAY("Sun");
private String dayOfWeek;
private DayOfWeek(String dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
public String toString() {
return this.dayOfWeek;
}
}
Now to make this enum really useful we should provide a method to convert a String back to an enum. If we simply used the supplied valueOf method in the DayOfWeekTest as follows:
public class DayOfWeekTest {A java.lang.IllegalArgumentException: No enum const class DayOfWeek.Tue is thrown as the valueOf method expects the full name of the enum constant; For example TUESDAY. A new method is needed, therefore out final enum becomes:
public static void main(String[] args) {
DayOfWeek mon = DayOfWeek.MONDAY;
System.out.println(mon.toString());
DayOfWeek tue = DayOfWeek.valueOf("Tue");
System.out.println(tue.toString());
}
}
public enum DayOfWeek {
MONDAY("Mon"), TUESDAY("Tue"), WEDNESDAY("Wed"), THURSDAY("Thu"), FRIDAY("Fri"), SATURDAY("Sat"), SUNDAY("Sun");
private String dayOfWeek;
private DayOfWeek(String dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
public String toString() {
return this.dayOfWeek;
}
public static DayOfWeek getValue(String dayOfWeek) {
for (DayOfWeek dow : DayOfWeek.values()) {
// Use equalsIgnoreCase to make the getValue method a little more robust
if (dow.toString().equalsIgnoreCase(dayOfWeek)) {
return dow;
}
}
return null;
}
}
We then change the valueOf method in the DayOfWeekTest to the getValue method as follows:
public class DayOfWeekTest {Run the program and Voila!
public static void main(String[] args) {
DayOfWeek mon = DayOfWeek.MONDAY;
System.out.println(mon.toString());
DayOfWeek tue = DayOfWeek.getValue("Tue");
System.out.println(tue.toString());
}
}
$ java DayOfWeekTest
Mon
Tue