在我的 Java 项目中,我需要处理一些字符串(一次大约 10-30 个)。我想要一个数据结构来保存它们,具有如下属性:
- 可以为每个字符串分配一个唯一的名字
- 唯一名称可以在代码中使用,就像它们是变量一样,支持 IDE 自动完成,无需调用 getValue() 或 toString() 等。
- 可以遍历数据结构中的每个值
在实践中,我希望代码看起来像这样:
MagicalDataStructure<String> mds = new MagicalDataStructure(
FirstString = "foo",
SecondString = "bar",
);
/*
This section would output:
foo
bar
*/
for (String value : mds) {
System.out.println(value);
}
/*
This section would output:
The first value is: foo
*/
System.out.println("The first value is: " + FirstString);
我考虑过的事情:
- 一堂充满静态期末的类(class)。这满足了#1 和#2,但我不能对它们进行迭代——至少不能不求助于 dark-mojo 反射。
- 字典。这满足 #1 和 #3,但键不能自动完成,并且访问值涉及额外的语法。
- 枚举。这也解决了#1 和#3,但是访问字符串值需要一些额外的代码。
是否有数据结构、库等可以满足我的需求?
最佳答案
为此,我肯定会喜欢 map :
public enum PagePath {
PATH1,
PATH2,
// etc.
}
public static final Map<PagePath, String> ALL_PATHS;
static {
Map<PagePath, String> paths = new EnumMap<>(PagePath.class);
paths.put(PagePath.PATH1, "/html/div[0]/h1");
paths.put(PagePath.PATH2, "/html//form/input[id='firstname']");
// etc.
// Make sure no one breaks things by removing entries
// or by adding enum constants while forgetting to account
// for them in the above Map.
if (!paths.keySet().equals(EnumSet.allOf(PagePath.class))) {
throw new RuntimeException(
"Map does not have entries for all PagePath constants!");
}
ALL_PATHS = Collections.unmodifiableMap(paths);
}
正如您所提到的,另一种可能性是使用字符串常量。您可以将这些常量的初始化放在“所有值”列表的初始化中,以确保它们都不会被遗忘:
public static final String PATH1;
public static final String PATH2;
// etc.
public static final Collection<String> ALL_PATHS;
static {
ALL_PATHS = Collections.unmodifiableCollection(Arrays.asList(
PATH1 = "/html/div[0]/h1",
PATH2 = "/html//form/input[id='firstname']",
// etc.
));
}
如果有人删除常量,他们将被迫从 Arrays.asList 调用中删除它的初始化。如果有人添加一个常量,并使其与其他常量的声明保持一致,他们将被迫将其添加到 ALL_PATHS 列表中,因为不这样做将意味着它永远不会被初始化,而编译器会捕捉到这一点。
关于java - 枚举和字典之间的交叉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463922/