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

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

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

  1. public class ColumnRowIterator implements Iterator<Integer> {
  2. private Integer[][] dataset;
  3. private int rowIndex;
  4. private int columnIndex;
  5. private int index;
  6. public ColumnRowIterator(Integer[][] dataset) {
  7. this.dataset = dataset;
  8. }
  9. public int currentRow(){
  10. return rowIndex;
  11. }
  12. public int currentColumn(){
  13. return columnIndex;
  14. }
  15. @Override
  16. public boolean hasNext() {
  17. return rowIndex < dataset.length && columnIndex < dataset[rowIndex].length;
  18. }
  19. @Override
  20. public Integer next() {
  21. if (!hasNext())
  22. throw new NoSuchElementException();
  23. if(rowIndex == dataset.length-1){
  24. columnIndex++;
  25. rowIndex=0;
  26. }else {
  27. rowIndex++;
  28. }
  29. return dataset[(index % dataset.length)][(index++ / dataset.length)];
  30. }
  31. @Override
  32. public void remove() {
  33. throw new UnsupportedOperationException("Not yet implemented");
  34. }
  35. }

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

  1. Matrix(int rowIndex, int columnIndex, boolean defaultRowColumnIterator) {
  2. if(rowIndex > 0 && columnIndex > 0) {
  3. this.matrix = new Integer[rowIndex][columnIndex];
  4. this.rowIndex = rowIndex;
  5. this.columnIndex = columnIndex;
  6. this.index=0;
  7. this.defaultRowColumnIterator = defaultRowColumnIterator;
  8. for(int i = 0; i< rowIndex; i++)
  9. for(int j = 0; j< columnIndex; j++)
  10. this.matrix[i][j]=0;
  11. }
  12. else System.out.println("Los parámetros de la matriz no son válidos.");
  13. }
  14. ``` `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方法来示例化迭代器。

  1. public interface MatrixIterator extends Iterator<Integer> {
  2. int currentRow();
  3. int currentColumn();
  4. }
  1. public class Matrix {
  2. // fields, constructors, and other code
  3. private MatrixIterator matrixIterator() {
  4. return (this.defaultRowColumnIterator
  5. ? new RowColumnIterator(this.matrix)
  6. : new ColumnRowIterator(this.matrix));
  7. }
  8. private static final class ColumnRowIterator implements MatrixIterator {
  9. // implementation here
  10. }
  11. private static final class RowColumnIterator implements MatrixIterator {
  12. // implementation here
  13. }
  14. }
展开查看全部

相关问题