Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-如何放入多维HashMap_Java_Nullpointerexception_Hashmap - Fatal编程技术网

Java-如何放入多维HashMap

Java-如何放入多维HashMap,java,nullpointerexception,hashmap,Java,Nullpointerexception,Hashmap,我有这个三维哈希图 private HashMap<Integer, HashMap<Integer, HashMap<Integer, Chunk>>> chunks = new HashMap<Integer, HashMap<Integer, HashMap<Integer, Chunk>>>(); 怎么了?初始化时,只初始化“外部”映射。以下是您必须做的: private Map<Integer, Ma

我有这个三维哈希图

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

怎么了?

初始化时,只初始化“外部”映射。以下是您必须做的:

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));
private Map chunks=new HashMap();
Map inner1=新的HashMap();
chunks.put(x,inner1);
Map inner2=新的HashMap();
inner1.put(y,inner2);
inner2.put(z,新块(x,y,z,param1,param2));

请注意,如果可能,您应该使用接口“Map”而不是实现“HashMap”。

重新建模您的应用程序

使用三个层次的HashMaps意味着同时处理三个层次的抽象。这是非常乏味和容易出错的

如果您能够将结构规范化到只需要两个级别,那么您可以使用Google的数据结构,这是二维地图的外观。这个数据结构已经解决了为您创建和访问各个地图层次结构的问题,因此您可以专注于类实际想要做的事情


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

您肯定应该创建一个新的
类来建模“块”,你说的建模是什么意思?所有的编程本质上都是为你正在解决的问题创建一个模型。目前你的“块”模型是一个整数到整数的映射到整数到块的映射;坦率地说,除了作者之外,任何人都读不懂。解决问题的面向对象方法是创建一个新类(或一组类),通过将问题分解为更小、更易于管理的块来建模。我将尝试这个方法。你能简单地解释一下为什么我更喜欢使用Map而不是HashMap吗?通常你应该使用通用接口定义,因为使用你的Map的方法或类并不关心实际的实现是什么。它可以是HashMap、TreeMap或任何类型的映射。然后,如果您想在以后更改实现,只需在一个地方进行更改。@KaareZ阅读Joshua Bloch的有效Java。特别是第52项,“通过其接口引用对象”。在谷歌上搜索章节名称,你还可以找到一些合理的摘要
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));