java - 如何在两个迭代器之间切换?
问题描述
我有两个像这样创建的不同迭代器:
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;
}
解决方案
假设您想要访问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
}
}
推荐阅读
- python - tensorflow 的 Dataset.list_files 函数中的“/*/*”是什么意思?
- python - 衡量运行时最佳实践 (Python)
- git - 在 GitHub 拉取请求中更改提交消息
- java - 如何在 IntelliJ 中显示文件结构(意外删除后)
- reactjs - 反应:你怎么知道哪个变量导致 componentDidUpdate() 被触发?
- sql - 将月费率除以日记录在SQL Server中基于getdate()和会计闰年的查询
- typescript - 映射保留参数类型的函数数组。TypeScript v4 中的可变元组类型可以改善这一点吗?
- sql - 在 SQL 中透视数据并返回多个关联列
- javascript - 从 Python 在网页上运行 JS
- javascript - express nodejs POST请求表单输入法