Java Enum example
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public class EnumExample{
public static void main(String args[]){
// To Get the 'Day' by Abbreviation:
System.out.println("1 ="+Day.get("Su"));
System.out.println("2 ="+Day.findByAbbr("Su"));
// To get 'Day' name in String:
System.out.println("3 ="+Day.valueOf("SUNDAY").toString());
// To Get the Abbreviation by 'Day':
System.out.println("4 ="+Day.SUNDAY.getAbbreviation());
System.out.println("5 ="+Day.valueOf("SUNDAY").getAbbreviation());
}
}
/**
* Usage:
* 1. To Get the 'Day' by Abbreviation: Day.get("Su"))<br/>
* 2. To Get the Abbreviation by 'Day': <br/>
* Day.SUNDAY.getAbbreviation();<br/>
* OR <br/>
* Day.valueOf("SUNDAY").getAbbreviation(); <br/>
* 3. To get 'Day' name in String:<br/>
* Day.valueOf("SUNDAY").toString();
*/
enum Day {
//Enum types
SUNDAY("Su"), MONDAY("Mo"), TUESDAY("Tu"), WEDNESDAY("We"), THURSDAY("Th"), FRIDAY("Fr"), SATURDAY("Sa");
//internal state
private final String abbreviation;
// Reverse-lookup map for getting a day from an abbreviation
private static final Map<String, Day> lookup_0 = new HashMap<String, Day>();
// Populate the lookup table on loading time
static {
for (Day d : Day.values()) {
lookup_0.put(d.getAbbreviation(), d);
}
}
//Alternative way populating lookup table
/*
static {
for (Day d : EnumSet.allOf(Day.class)) {
lookup_0.put(d.getAbbreviation(), d);
}
}*/
//Constructor
private Day(final String abbreviation) {
this.abbreviation = abbreviation;
}
public String getAbbreviation() {
return abbreviation;
}
// This method can be used for reverse lookup purpose
public static Day get(String abbreviation) {
return (Day)lookup_0.get(abbreviation);
}
public static Day findByAbbr(String abbreviation){
for(Day d : values()){
if( d.abbreviation.equals(abbreviation)){
return d;
}
}
return null;
}
}
No comments:
Post a Comment