如何在两个迭代器之间切换?

vmdwslir  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(358)

我创建了两个不同的迭代器,如下所示:

public class ColumnRowIterator implements Iterator<Integer> {

private Integer[][] dataset;
private int rowIndex;
private int columnIndex;
private int index;

public ColumnRowIterator(Integer[][] dataset) {
    this.dataset = dataset;
}

public int currentRow(){
    return rowIndex;
}

public int currentColumn(){
    return columnIndex;
}

@Override
public boolean hasNext() {
    return rowIndex < dataset.length && columnIndex < dataset[rowIndex].length;
}

@Override
public Integer next() {
    if (!hasNext())
        throw new NoSuchElementException();
    if(rowIndex == dataset.length-1){
        columnIndex++;
        rowIndex=0;
    }else {
        rowIndex++;
    }
    return dataset[(index % dataset.length)][(index++ / dataset.length)];

}

@Override
public void remove() {
    throw new UnsupportedOperationException("Not yet implemented");
}

}

一个先穿过列,另一个先穿过行。然后我有另一门课叫 Matrix 使用不同的方法(如打印矩阵或更改某些值)。矩阵的构造函数如下:

Matrix(int rowIndex, int columnIndex, boolean defaultRowColumnIterator) {
    if(rowIndex > 0 && columnIndex > 0) {
        this.matrix = new Integer[rowIndex][columnIndex];
        this.rowIndex = rowIndex;
        this.columnIndex = columnIndex;
        this.index=0;
        this.defaultRowColumnIterator = defaultRowColumnIterator;
        for(int i = 0; i< rowIndex; i++)
            for(int j = 0; j< columnIndex; j++)
                this.matrix[i][j]=0;
    }
    else System.out.println("Los parámetros de la matriz no son válidos.");
}
``` `defaultRowColumnIterator` 是一个布尔值,用于在迭代器之间切换。因此,有没有可能更改迭代器,以便方法中的实现不会更改。例如,用这两种可能性来代替写ifs( `RowColumnIterator iterator = new RowColumnIterator(this.matrix);` )像这样做一次 `Iterator iterator = new iterator(this.matrix);` 或者类似的东西。

public Integer[][] copyOfMatrix(){
Integer[][] copy = new Integer[this.rowIndex][this.columnIndex];
RowColumnIterator iterator = new RowColumnIterator(this.matrix);
while(iterator.hasNext()) {
copy[iterator.currentRow()][iterator.currentColumn()] = iterator.next();
}
return copy;
}

kq4fsx7k

kq4fsx7k1#

假设你想进入 currentRow() 以及 currentColumn() 方法,您应该创建一个接口。
然后我建议您创建一个helper方法来示例化迭代器。

public interface MatrixIterator extends Iterator<Integer> {
    int currentRow();
    int currentColumn();
}
public class Matrix {

    // fields, constructors, and other code

    private MatrixIterator matrixIterator() {
        return (this.defaultRowColumnIterator
                ? new RowColumnIterator(this.matrix)
                : new ColumnRowIterator(this.matrix));
    }

    private static final class ColumnRowIterator implements MatrixIterator {
        // implementation here
    }

    private static final class RowColumnIterator implements MatrixIterator {
        // implementation here
    }
}

相关问题