gpt4 book ai didi

java - 类内的私有(private)枚举

转载 作者:行者123 更新时间:2023-11-29 08:29:34 26 4
gpt4 key购买 nike

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

在这个类中,我的 map 键是 NearestNeighbour, Bilinear, Bicubic4x4 所以我创建了一个私有(private)枚举并从 map 中检索值,如下所示 properties.get(InterpolationMode.Bilinear.getMode( ));

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

最佳答案

为此目的使用枚举完全没问题。您可以考虑使用枚举作为键(而不是字符串)并使用 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的优点是更简洁高效。

关于java - 类内的私有(private)枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49409744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com