Oftentimes, we need a fixed set of constants in our application. Examples might include the days of the week and the colors in a rainbow. To create such sets, we create integer patterns in our code. In this post, we discuss these integer patterns—how they are created and what their drawbacks are—before looking at the new enum construct.

Creating Integer Patterns for Enumerations

To declare enumerations for the colors of a rainbow, we would declare the following sort of int pattern:

·         public static final int COLOR_VIOLET = 0;

·         public static final int COLOR_INDIGO = 1;

·         public static final int COLOR_BLUE = 2;

Using such an int pattern poses many problems. In the first place, they are not typesafe. We could simply pass in any int value where a color in a rainbow is required. Even worse, we could do some arithmetic on these colors, which is obviously meaningless.

Second, to avoid name collisions with other constants in our application, we need to prefix their names, which is why the COLOR prefix is used in this example.

Third, such enumeration types are brittle in the sense that they are compiled on the client. Later on, if we change their order or simply add a new constant, the client would require a recompilation. If not recompiled, the client would behave unpredictably. For example, Sir Isaac Newton originally named only five primary colours (red, yellow, green, blue, and violet) in a rainbow. Later he added orange and indigo. Thus, even in such rare cases, the constants in an enumeration type could change.

Finally, if we print these constants in our program, what we get are simply integer values, which don’t convey what they represent or their type.

The enum Type

The issues we just discussed are now resolved with the introduction of the enum type in J2SE 5.0. The enum type in Java is more enhanced compared to similar-looking enumerations in other languages. In most other languages, an enumeration is simply a list of named integer constants.

In Java, enum is a full-fledged class and thus offers all the benefits of declaring a class, as discussed so far in this post. It allows us to add arbitrary methods and fields, to implement arbitrary interfaces, and much more.

The objects of the enum type can be compared to each other and can be serialized—the serialization withstands arbitrary changes in the enum type. To illustrate these benefits, we will examine and implement some concrete examples in the next post.

  Modified On Nov-29-2017 10:08:43 PM

Leave Comment