gpt4 book ai didi

java - 如何正确地延迟初始化 Map of Map 的 Map?

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:29 30 4
gpt4 key购买 nike

这可能是一种不好的做法,但我还没有找到更好的解决方案来解决我的问题。所以我有这张 map

// Map<state, Map<transition, Map<property, value>>>
private Map<String, Map<String, Map<String, String>>> properties;

我想初始化它,这样我就不会得到 NullPointerException

properties.get("a").get("b").get("c");

我试过这个但我没有工作(显然)

properties = new HashMap<String, Map<String, Map<String,String>>>();

我试过的其他东西没有编译。

此外,如果您对如何避免这种嵌套映射有任何想法,我将不胜感激。

最佳答案

在我看来,您需要创建自己的 Key 类:

public class Key {
private final String a;
private final String b;
private final String c;
public Key(String a, String b, String c) {
// initialize all fields here
}

// you need to implement equals and hashcode. Eclipse and IntelliJ can do that for you
}

如果您实现自己的键类,您的 map 将如下所示:

Map<Key, String> map = new HashMap<Key, String>();

当您在 map 中查找内容时,您可以使用:

map.get(new Key("a", "b", "c"));

上述方法不会抛出 NullPointerException。

请记住,要使此解决方案起作用,您需要覆盖 Key 类中的 equals 和 hashcode。有帮助here .如果您不覆盖 equals 和 hashcode,则具有相同元素的新键将不会与映射中的现有键匹配。

还有其他可能的解决方案,但在我看来,实现您自己的 key 是一个非常干净的解决方案。如果您不想使用构造函数,您可以使用静态方法初始化您的 key 并使用类似的方法:

Key.build(a, b, c)

这取决于你。

关于java - 如何正确地延迟初始化 Map of Map 的 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9063641/

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