Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EnumMap or HashMap if lookup key is a String

I'm trying to weigh the pros and cons of using an EnumMap over a HashMap. Since, I will always be looking up using a String, it seems that a HashMap with a String key would be the right choice. However, an EnumMap seems like better design because it conveys my intent to restrict keys to a specific enumeration. Thoughts?

Here is a make-believe example, showing how I will be using the Map:

enum AnimalType { CAT, DOG } interface Animal {} class Cat implements Animal {} class Dog implements Animal {}  public class AnimalFactory {      private static final Map<AnimalType, Animal> enumMap              = new EnumMap<AnimalType, Animal>(AnimalType.class);     // versus     private static final Map<String, Animal> stringMap              = new HashMap<String, Animal>();      static {         enumMap.put(AnimalType.CAT, new Cat());         enumMap.put(AnimalType.DOG, new Dog());         stringMap.put("CAT", new Cat());         stringMap.put("DOG", new Dog());     }     public static Animal create(String type) {         Animal result = enumMap.get(AnimalType.valueOf(type));         Animal result2 = stringMap.get(type);         return result;     } } 

Assume that the AnimalType enum and map will ONLY be used by the AnimalFactory to create animals and nowhere else.

Which Map should I use?

like image 754
dogbane Avatar asked May 04 '12 08:05

dogbane


People also ask

Can HashMap have string as key?

String is as a key of the HashMap When you pass the key to retrieve its value, the hash code is calculated again, and the value in the position represented by the hash code is fetched (if both hash codes are equal).

Why EnumMap is faster than HashMap?

EnumMap is much faster than HashMap. All keys of each EnumMap instance must be keys of the same enum type. EnumMap doesn't allow inserting null key if we try to insert the null key, it will throw NullPointerException. EnumMap is internally represented as arrays therefore it gives the better performance.

What is the use of EnumMap in Java?

Methods of Java EnumMap class It is used to clear all the mapping from the map. It is used to copy the mapped value of one map to another map. It is used to check whether a specified key is present in this map or not. It is used to check whether one or more key is associated with a given value or not.


1 Answers

If all valid keys can be enumerated, I would use that as it ensures you are always working with a valid value.

It can also avoid confusion as String can be used for lots of things and is easy to turn an "Animal" string into a string used for something else. As enum types are not interchangable with other types in general (unless you use a common interface), there is less chance of error in coding.

like image 108
Peter Lawrey Avatar answered Oct 20 '22 13:10

Peter Lawrey