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?