implemented hasnext

This commit is contained in:
Johannes Schmelz 2024-06-14 08:08:10 +00:00
parent 93fb940a8c
commit dad5a33695
4 changed files with 10 additions and 50 deletions

Binary file not shown.

Binary file not shown.

View File

@ -2,72 +2,32 @@ package uebung09.iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Array2dIterator<T> implements Iterator<T>{
private T[][] array;
private ArrayList<T> list;
private int index = 0;
private int row = 0;
private int col = 0;
public Array2dIterator(T[][] array) {
this.array = array;
list = flatten();
}
@Override
public boolean hasNext() {
// for (int i = 0; i < array.length; i++) {
// for (int j = 0; j < array[i].length; j++) {
// if (array[i][j+1] != null) {
// return true;
// }
// if (array[i+1][j] != null) {
// return true;
// }
// }
// }
// return false;
if (list.get(index)) {
return true;
} else {
return false;
while(row < array.length && (array[row] == null || col >= array[row].length)) {
row++;
col = 0;
}
// return true;
return row > array.length;
}
@Override
public T next() {
// for (int i = 0; i < array.length; i++) {
// for (int j = 0; j < array[i].length; j++) {
// if (array[i][j+1] != null) {
// return array[i][j+1];
// }
// }
// if (array[i+1][0] != null) {
// return array[i+1][0];
// }
// }
// return null;
return list.get(index++);
if (!hasNext()) {
throw new NoSuchElementException();
}
private ArrayList<T> flatten(){
ArrayList<T> list = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
list.add(array[i][j]);
}
}
return list;
return array[row][col++];
}
}