HashMap问题:填充后缺少条目



大家好,感谢大家的阅读。我在Java中遇到了Hashmap的问题。HashMap被认为取代了2d数组,因此数组索引对被用来计算键。映射在双for循环中填充。相关的代码片段如下所示:

这是"填充物"地图和随后的尺寸测试。

HashMap<Integer, Cell> field = new HashMap<Integer, Cell>();
// Fill field object with cells
for (int colCnt = 0; colCnt < cols; colCnt++) {
for (int rowCnt = 0; rowCnt < rows; rowCnt++) {
Cell cell = new Cell(colCnt, rowCnt);
field.put(cell.hashCode(), cell);
}
}
System.out.println("cells: "+field.size());

这里是Cell对象的构造函数:

public Cell(int column, int row) {
if (row < 0 || column < 0) {
throw new IllegalArgumentException("Cell must not have negative coordinates");
}
this.row = row;
this.column = column;
this.status = false;
}

这里是HashCode(来自Cell类)的方法:

public int hashCode() {
return Objects.hash(column, row);
}

,其中参数column和row指向局部final int变量,它们是类字段,在构造函数中设置。

问题是:只要column参数大于1,并且row参数大于31且大于column参数,就不再映射所有单元格。仔细一看,我发现,只有最后一列(当col>1)已满行号。除最后一列外的所有列都被截断为31个元素。但是,如果column参数比行大得多,则所有参数都可以,例如1000列和5行导致5000个单元格。另一方面,5列和1000行只给出1124个单元格。如果同时增加列和行,它会一直工作到31列和31行,结果是961个单元格。32列32行,我得到993单元格,而不是1024。

谁能给我点提示,出什么事了?HashMap列表设置默认参数,意味着初始16个字段,加载0.75。

非常感谢!

hashCode不是唯一标识符,因此不能依赖它作为Map键。一个简单的选择是将列和行连接为字符串,并使用Map<String,Cell>

public class Cell {
... stuff ...
public String key() {
return String.format("%d-%d", column, row);
}
}

最新更新