EnumMap or HashMap if lookup key is a String

后端 未结 4 1862
花落未央
花落未央 2021-02-03 21:45

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 tha

4条回答
  •  孤独总比滥情好
    2021-02-03 22:48

    Key Of Map should be unmodifiable and Unique and this can be guranteed using Enum.

    Also managing it would be easier and less error prone as compare to managing String.

    So Go For EnumMap.

    Also as we have advanced enums, we can attach many other information and operations with the keys itself.

    enum AnimalType {
    
      Dog("I am dog and I hate cats", true), 
      CAT("I am cat and I love to eat rats", true),
      RAT("I am a mouse and I love tearing human cloths apart", false) ;
    
      private final String description;
      private final boolean isHelpFullToHuman;
    
      private AnimalType(String description , boolean isHelpFullToHuman) {
         this.description = description;
         this.isHelpFullToHuman = isHelpFullToHuman;
      }
    
      public boolean isHelpFullToHuman() {
         return isHelpFullToHuman;
      }
    
      public String getDescription() {
         return description;
      }
    
    }
    

提交回复
热议问题