Friday, July 19, 2013

Java: Maps with enums as keys

Life is hard and world is big, but sometimes when we see another person where we don't expected him to be, we say "how little the world is" (at least this happens in Italy).
I think that world is really little at least for another reason :-p

Which one?! Simple!
A lot of people use HashMap (or other map implementations) filled with enum keys instead of using EnumMap.

Java standard SDK provides java.util.EnumMap specifically to manage maps with enums as keys, this map is size optimized and potentially quicker than HashMap counterpart. Furthermore an EnumMap mantains the natural order of Enum.

That's all, so lets try to change your code from
public class EnumMapMain {
    
    enum Tires {
        SOFT,
        MEDIUM,
        HARD
    }
    
    public static void main(String[] args) {
        Map tiresToDescription = new HashMap();
        tiresToDescription.put(Tires.HARD, "Worst grip of all tires but with a greate durability");
        tiresToDescription.put(Tires.MEDIUM, "Medium grip and medium durability");
        tiresToDescription.put(Tires.SOFT, "A lot of grip but usefull only for few laps");
        
        StringBuilder buildDescription = new StringBuilder("Tires Types:");
        for (Tires tire : Tires.values()) {
            buildDescription.append("\n\t").append(tire).append("\t-->\t").append(tiresToDescription.get(tire));
        }
        System.out.println(buildDescription.toString());
    }
}
to
public class EnumMapMain {
    
    enum Tires {
        SOFT,
        MEDIUM,
        HARD
    }
    
    public static void main(String[] args) {
        Map tiresToDescription = new EnumMap(Tires.class);
        tiresToDescription.put(Tires.HARD, "Worst grip of all tires but with a greate durability");
        tiresToDescription.put(Tires.MEDIUM, "Medium grip and medium durability");
        tiresToDescription.put(Tires.SOFT, "A lot of grip but usefull only for few laps");
        
        StringBuilder buildDescription = new StringBuilder("Tires Types:");
        for (Tires tire : Tires.values()) {
            buildDescription.append("\n\t").append(tire).append("\t-->\t").append(tiresToDescription.get(tire));
        }
        System.out.println(buildDescription.toString());
    }
}

It's simple and unpainful! It brings some memory and performance improvements to your code ;-)

Related posts:

No comments:

Post a Comment