Make delicious recipes!

EnumMap


EnumMap is a special Map whose keys can only be enum values.
The enum values belong to a single enum only.
Enum maps are represented internally as arrays which makes them extremely compact and efficient.


Consider the below code which compares EnumMap with HashMap.
import java.util.EnumMap;
import java.util.HashMap;

public class EnumMapTest
{
    /* Declare some enum. More the number of values in the enum, more effective is the EnumMap */
    static enum Colors
    {
        RED("Red", 1), BLUE("Blue", 2), GREY("Grey", 3), GREEN("Green", 4), YELLOW("Yellow", 5), ORANGE("Orange", 6);

        String color;
        Integer code;

        Colors(String color, Integer code)
        {
            this.color = color;
            this.code = code;
        }
    };


    /* Main function to check performance */
    public static void main(String[] args)
    {
        HashMap<Colors, String> hmap = new HashMap<Colors, String>();
        EnumMap<Colors, String> emap = new EnumMap<Colors, String>(Colors.class);

        /* Check HashMap performance */
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10 * 1000 * 1000; i++)
        {
            Colors c = Colors.values()[i % Colors.values().length];
            hmap.put(c, "");
            hmap.get(c);
        }
        long end1 = System.currentTimeMillis();
        System.out.println("HashMap took " + (end1 - start) + " milliseconds.");


        /* Check EnumMap performance */
        for (int i = 0; i < 10 * 1000 * 1000; i++)
        {
            Colors c = Colors.values()[i % Colors.values().length];
            emap.put(c, "");
            emap.get(c);
        }
        long end2 = System.currentTimeMillis();
        System.out.println("EnumMap took " + (end2 - end1) + " milliseconds.");
    }
}

Result:
HashMap took 1016 milliseconds.
EnumMap took 626 milliseconds.








Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal