遍历矩阵的元素

时间:2019-04-07 19:58:55

标签: java

我正在编写由矩阵(2D数组)支持的自定义哈希图实现。我想遍历元素并打印它们,但想避免打印空元素。

哈希图仅支持Integers并将哈希码作为输入mod 10计算。它将这些Integer存储在适当的hashcode索引内,并且通过迭代子数组并将Integer放在子数组的下一个可用索引中来解决冲突。如果超过了给定子数组的最大索引,它将创建一个新数组,其大小为原始数组的1.5倍,然后将元素复制到该数组。

问题在于, ObservableList<String> items = FXCollections.observableArrayList(array[0]); tableColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue())); table.setItems(items); ObservableList<String> items2 = FXCollections.observableArrayList(array[1]); tableColumn2.setCellValueFactory(data -> new SimpleStringProperty(data.getValue())); table.setItems(items2); 每次等于子数组长度时,System.out.print都会抛出ArrayIndexOutOfBoundsException,因此while循环无法按预期工作。

我已经尝试过更改while循环,以使迭代器变量应该小于每个子数组的最大索引。将条件更改为iterator可以避免出现异常,但是Java不会打印每个子数组的最后一个元素。

iterator < array[i].length - 1

输出应该类似于

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, ]...

2 个答案:

答案 0 :(得分:0)

将检查顺序反转为while(iterator

答案 1 :(得分:0)

更改此行应解决此问题:

     while (array[i][iterator] != null && iterator < array[i].length) {

对此:

     while (iterator < array[i].length && array[i][iterator] != null) {