Java In-line Initialization of a Map in the Constructor of an Enum Constant

With Java 5.0 enums became much more powerful, click here for an overview.

I am working on a project that is using an enum to keep track of an attribute of one of my objects and wanted to initialize a HashMap inline in the call to the enum’s constructor. Such was my delight to find out that using a simple initializer block that it was a snap.

Here is the relevant snippet of code that illustrates the syntax:

public enum MediaFileType{
    IMAGE( new HashMap<String, String>() {
            {
                put(“.jpg”, “image/jpeg”);
                put(“.jpeg”, “image/jpeg”);
            }
        } );

Leave a Reply