Java - 如何放入多维HashMap

Java - How to put in a multi dimensional HashMap

我有这个三维 HashMap。

   private HashMap<Integer, HashMap<Integer, HashMap<Integer, Chunk>>> chunks = new HashMap<Integer, HashMap<Integer, HashMap<Integer, Chunk>>>();

当我使用它来放入 'Chunk' 时,我得到一个 NullPointerException。

chunks.get(x).get(y).put(z, new Chunk(x, y, z, param1, param2));

怎么了?

通过初始化,您只需初始化 "outer" 地图。这是你必须做的:

private Map<Integer, Map<Integer, Map<Integer, Chunk>>> chunks = new HashMap<Integer, Map<Integer, Map<Integer, Chunk>>>();

Map<Integer, Map<Integer, Chunk>> inner1 = new HashMap<Integer, Map<Integer, Chunk>>();
chunks.put(x, inner1);

Map<Integer, Chunk> inner2 = new HashMap<Integer, Chunk>();
inner1.put(y, inner2);

inner2.put(z, new Chunk(x, y, z, param1, param2));

请注意,您应该尽可能使用接口 'Map' 而不是实现 'HashMap'。

重新建模您的应用程序。

使用三级HashMap意味着同时处理三级抽象。这非常繁琐且容易出错。

如果您能够将结构标准化到只需要两个级别,则可以使用 Table data structure from Google's Guava library,它是二维映射的 Facade。这种数据结构已经为您解决了创建和访问各个地图层次结构的问题,因此您可以专注于 class 真正想做的事情。

如果你不想使用外部库,你将不得不自己编写一个类似的数据结构。确保将其创建为核心应用程序之外的单独 class / 接口,并对其进行大量单元测试。但是,将三层数据结构与核心业务逻辑混合意味着违反面向对象设计的基本原则之一的内聚性。