首页 > 解决方案 > 如何在两个迭代器之间切换?

问题描述

我有两个像这样创建的不同迭代器:

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是一个布尔值,是迭代器之间的切换。那么是否可以更改迭代器以使方法中的实现不改变。例如,不要用 2 种可能性 ( ) 写 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;
}

标签: javaiterator

解决方案


假设您想要访问currentRow()currentColumn()方法,您应该使用它们创建一个接口。

然后,我建议您创建一个辅助方法来实例化迭代器。

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
    }
}

推荐阅读