Enum can do a lot more than you think

Aman Agrawal
2 min readMay 30, 2020

--

Hello guys, this time I thought of picking some simple but interesting topics that are Enums and EnumMap. Let us start with enums.

As we all know, an enum is used to declare a set of constants. For example

The above program is the simplest example of an enum where I have declared a few constants and made use of commonly used methods. Do you know it can do a lot more? Let us look at it one by one

  • You can declare constructors but access modifiers of those constructors can either be private or default level. These constructors cannot be invoked in the code. They are always called automatically when the enum is initialized.

In the above example, I have declared a parameterized constructor. Each constant is an instance of the enum Fruit. If no constructor is provided, it calls the default constructor.

  • Java enums implicitly extend the java.lang.Enum class. Therefore, java enum cannot extend any other class. But enums can implement different interfaces.

As you can see I have declared an interface and each enum constant is implementing the interface.

  • Java enums implicitly implement the java.lang.Comparable and the java.io.Serializable interface.
  • We can’t instantiate an enum using the new operator.
  • Like classes, an enum can also have methods and fields.
  • You can use the “==” operator to compare 2 constants since enum constants are final.
  • You can iterate over enum constants.

I hope you guys find this as easy. Do use it in your code. Now my next topic is on EnumMap.

An EnumMap is a specialized implementation of the Map interface for enumeration types. It comes into handy when you want to define maps with enum types as a key. All of the keys in the enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are internally represented as arrays. In short, an EnumMap is an optimized map implementation (Quicker hash computation since all possible keys are known in advance) exclusively for enums as a key. It is an ordered collection and they are maintained in the natural order of their keys ie the order in which enum constants are defined inside enum type.

That’s it from this blog. I hope you guys read all my previous blogs. If not, please do read.

Thank You.

--

--

No responses yet