title: EnumMap or HashMap if lookup key is a String
body: <p>I'm trying to weigh the pros and cons of using an <code>EnumMap</code> over a <code>HashMap</code>. Since, I will always be looking up using a <code>String</code>, it seems that a <code>HashMap</code> with a <code>String</code> key would be the right choice. However, an <code>EnumMap</code> seems like better design because it conveys my intent to restrict keys to a specific enumeration. Thoughts?</p>
  
  <p>Here is a make-believe example, showing how I will be using the <code>Map</code>:</p>
  
  <pre><code>enum AnimalType { CAT, DOG }
  interface Animal {}
  class Cat implements Animal {}
  class Dog implements Animal {}
  
  public class AnimalFactory {
  
      private static final Map&lt;AnimalType, Animal&gt; enumMap 
              = new EnumMap&lt;AnimalType, Animal&gt;(AnimalType.class);
      // versus
      private static final Map&lt;String, Animal&gt; stringMap 
              = new HashMap&lt;String, Animal&gt;();
  
      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;
      }
  }
  </code></pre>
  
  <p>Assume that the <code>AnimalType</code> enum and map will ONLY be used by the <code>AnimalFactory</code> to create animals and nowhere else.</p>
  
  <p>Which <code>Map</code> should I use?</p>