Skip to main content

Posts

Showing posts with the label Enum

How to reverse lookup an enum from its values in Java?

-- Sometime, you need to lookup an enum from its value (may be a integer, string or other types). This reverse lookup can be easily implemented by using a static java.util.Map inside your enum class. For example, import java.util.HashMap; import java.util.Map; public enum Day {      SUNDAY(0),      MONDAY(1),      TUESDAY(2),      WEDNESDAY(3),      THURSDAY(4),      FRIDAY(5),      SATURDAY(6);        private static final Map lookup = new HashMap();      static {          //Create reverse lookup hash map          for(Day d : Day.values())              lookup.put(d.getDayValue(), d);      }

What is the difference between an enum type and java.lang.Enum?

-- An enum type, also called enumeration type, is a type whose fields consist of a fixed set of constants. The purpose of using enum type is to enforce type safety. While java.lang.Enum is an abstract class, it is the common base class of all Java language enumeration types. The definition of Enum is: public abstract class Enum> extends Object implements Comparable, Serializable All enum types implicitly extend java.lang.Enum. The enum is a special reference type, it is not a class by itself, but more like a category of classes that extends from the same base class Enum. Any type declared by the key word "enum" is a different class. They easiest way to declare a enum type is like: public enum Season {     SPRING, SUMMER, AUTUM, WINTER }

"Enums" Concepts in Java

-- In prior releases, Java does not support the concept of user-defined enumerated types. What is an enumerated type? An enumerated type is a type whose legal values consist of a fixed set of constants. The standard way to represent an enumerated type was the int Enum pattern, for example, to define the four seasons in a year: public class SEASON { public static final int WINTER = 0; public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; } This pattern has many problems, such as, not typesafe, no namespace, printed values are uninformative, and not convenient, etc. In 5.0, Java adds support for enumerated types. The new enum has a lot of advantages including: