课堂内的私人enum

时间:2018-03-21 15:00:45

标签: java enums

我有很多类,每个类都包含一个完全不同的搜索键的地图。每张地图平均有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());

问题是我有大约20个班级,每个班级都有自己的不同键的地图(它们没有关联)。全局包枚举对我来说没有意义,因为这些搜索键没有任何关联。在每个类中创建类似的私有枚举是一个好主意吗?或者有没有更好的方法来做到这一点,根本不使用枚举?

2 个答案:

答案 0 :(得分:4)

为此目的使用枚举是完全没问题的。您可以考虑使用枚举作为键(而不是字符串)并使用string(7) "`yeet` " 代替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"); 的优势在于它更紧凑,更高效。

答案 1 :(得分:0)

您是否只是为了保存不同的数据地图而创建了许多类?如果是这样,最好只创建一个类,然后从该类创建许多对象。

只要枚举具有真实含义(例如性别,银行帐户类型),就可以使用全局枚举。

相关问题