簡體   English   中英

班級內部的私人枚舉

[英]Private enum inside class

我有很多班級,每個班級都包含一張地圖,它們的搜索鍵完全不同。 每個地圖平均有4個項目=> 4個平均搜索關鍵字。

例:

class A
{
 private final static Map<String, String> properties;
 static
  {
    Map<String, String> tmp = new HashMap<>();
    tmp.put("NearestNeighbour", "INTER_NEAREST");
    tmp.put("Bilinear", "INTER_LINEAR");
    tmp.put("Bicubic4x4", "INTER_CUBIC");
    properties = Collections.unmodifiableMap(tmp);
  }

  private enum InterpolationMode
  {
    NN("NearestNeighbour"),
    Bilinear("Bilinear"),
    Bicubic("Bicubic");

    private String mode;
    InterpolationMode(String mode) {
      this.mode = mode;
    }

    public String getMode(){
      return mode;
    }
  }
}

在此類中,我的地圖鍵是NearestNeighbour, Bilinear, Bicubic4x4因此我創建了一個私有枚舉,並像這樣的properties.get(InterpolationMode.Bilinear.getMode());從地圖中檢索值properties.get(InterpolationMode.Bilinear.getMode());

問題是我大約有20個類,每個類都有自己的映射,這些映射具有不同的鍵(它們不相關)。 全局包枚舉對我來說沒有意義,因為這些搜索鍵沒有任何關系。 在每個類中創建一個像這樣的私有枚舉是一個好主意嗎? 還是有更好的方法做到這一點並且根本不使用枚舉?

為此目的使用枚舉是完全可以的。 您可以考慮使用枚舉作為鍵(而不是字符串),並使用EnumMap代替HashMap

Map<InterpolationMode, String> tmp = new EnumMap<>(InterpolationMode.class);
tmp.put(InterpolationMode.NN, "INTER_NEAREST");
tmp.put(InterpolationMode.Bilinear, "INTER_LINEAR");
tmp.put(InterpolationMode.Bicubic, "INTER_CUBIC");

EnumMap的優點是它更加緊湊和高效。

您是否正在創建許多類來容納不同的數據圖? 如果這樣,最好只創建一個類,然后從該類創建許多對象。

只要枚舉具有真實含義(例如性別,銀行帳戶類型),就可以使用全局枚舉。

暫無
暫無

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

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