簡體   English   中英

使用地圖與枚舉

[英]using Map vs Enum


我需要保留一個映射,該映射查找給定String的一些屬性。 對於下面這樣的示例,我需要根據該動物的描述獲取該動物的可能顏色。 我有“四腳動物”-不是“ CAT”-並且需要找到布朗和灰色。
將其保留在枚舉中可使代碼更易於維護和易於閱讀,但每次我嘗試查找顏色時遍歷所有枚舉值都會產生額外的開銷。 而且,每當我需要獲取顏色列表時,都會創建一個新的數組。
我的問題是,這些額外費用會分別影響20左右大小的Animal枚舉和String設置(已提供映射說明)的性能嗎? 還想知道JVM是否優化了這些Arrays.asList調用。
或您會建議的任何其他設計解決方案?
如果您能推薦一個來源來閱讀更多有關這些性能問題的信息,將對它產生多大的影響,我們將不勝感激。
謝謝!

public enum AnimalsEnum{
    CAT("An animal with four legs"){
        @Override   
        public List<ColorsEnum> getPossibleColors(){
            return Arrays.asList(BROWN, GREY);
        }
    },
    BIRD("An animal with two legs and two wings"){
        @Override   
        public List<ColorsEnum> getPossibleColors(){
            return Arrays.asList(GREY, YELLOW, ORANGE);
        };
    };

    public List<ColorsEnum> getPossibleColors(){
        throw new AbstractMethodError();
    };
}


public enum ColorsEnum{
    ORANGE, BLUE, GREY, BROWN, YELLOW;
}

關於您的疑問“並且每當我需要獲取顏色列表時,都會創建一個新的數組”,您可以嘗試以下操作:

public enum AnimalsEnum
{
  CAT("An animal with four legs",
      EnumSet.of(ColorsEnum.BROWN, ColorsEnum.GREY)),
  BIRD("An animal with two legs and two wings",
       EnumSet.of(ColorsEnum.GREY, ColorsEnum.YELLOW, ColorsEnum.ORANGE));

  private AnimalsEnum(String              description,
                      EnumSet<ColorsEnum> possible_colors)
  {
    this.description = description;
    this.possible_colors = possible_colors;
  }

  public String getDescription()
  {
    return description;
  }

  public EnumSet<ColorsEnum> getPossibleColors()
  {
    return (possible_colors);
  }

  public static AnimalsEnum getAnimal(String description)
  {
    return (descr_map.get(description));
  }

  private String description;

  private EnumSet<ColorsEnum> possible_colors;

  private static HashMap<String, AnimalsEnum> descr_map;

  static
  {
    descr_map = new HashMap<String, AnimalsEnum>();
    for (AnimalsEnum animal : values())
    {
      descr_map.put(animal.getDescription(), animal);
    }    
  }

} // enum AnimalsEnum

編輯:
修改了答案,添加了一個靜態方法,該方法返回與其描述相對應的動物。

編輯2:
如果您不想為動物單獨保留Enum ,則可以嘗試以下方法:

public class AnimalColors extends HashMap<String, EnumSet<ColorsEnum>>
{
  private AnimalColors()
  {
    put("An animal with four legs", EnumSet.of(ColorsEnum.BROWN, ColorsEnum.GREY));
    put("An animal with two legs and two wings", EnumSet.of(ColorsEnum.GREY, ColorsEnum.YELLOW, ColorsEnum.ORANGE));
  }

  public static AnimalColors get()
  {
    return my_instance;
  }

  private static AnimalColors my_instance = new AnimalColors();

} // class AnimalColors

這僅僅是基於意見的。 由你決定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM