我正在编写一个由矩阵(二维数组)支持的自定义 hashmap 实现。我想遍历元素并打印它们,但想避免打印空元素。
hashmap 只支持整数并计算哈希码作为输入 mod 10。它将这些整数存储在适当的哈希码索引中,通过迭代子数组并将整数放在子数组的下一个可用索引中来解决冲突。如果超过给定子数组的最大索引,它将创建一个大小为原始数组 1.5 倍的新数组,并将元素复制到该数组中。
问题是每次等于子数组长度时System.out.print
都会抛出一个,所以 while 循环没有按预期工作。ArrayIndexOutOfBoundsException
iterator
我已经尝试更改 while 循环,以便迭代器变量应该小于每个子数组的最大索引。将条件更改为iterator < array[i].length - 1
将避免异常,但 Java 不会打印每个子数组的最后一个元素。
public void print () {
int iterator = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == null)
continue;
System.out.print("[");
while (array[i][iterator] != null && iterator < array[i].length) {
System.out.print(array[i][iterator] + ", ");
iterator++;
}
System.out.println ("]");
iterator = 0;
}
}
输出应该是这样的
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, ]
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91, ]...
但实际输出是
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at regularexpression.HashMap.print(HashMap.java:42)
更改此行应该可以修复它:
while (array[i][iterator] != null && iterator < array[i].length) {
对此:
while (iterator < array[i].length && array[i][iterator] != null) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句