Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions src/designpatterns/iterator/Array3D.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package designpatterns.iterator;


import java.util.Iterator;
import java.util.NoSuchElementException;

public class Array3D<T> implements Iterator<T> {
private int index = 0;
private final T[][][] array3d;
private final int size;
private int matrix;
private int row;
private int col;

public Array3D(T[][][] array3d) {
this.array3d = array3d;
this.size = size(array3d);
this.matrix = 0;
this.row = 0;
this.col = 0;
}

private int prevMatrix;
private int prevRow;
private int prevCol;

private int size(T[][][] array3d) {
int counter = 0;
for (T[][] array2d: array3d) {
for (T[] array: array2d){
counter+=array.length;
}
}
return counter;
}

@Override
public boolean hasNext() {
return index < size;
}

@Override
public T next() {
if (index >= size) {
throw new NoSuchElementException();
}
T element = array3d[matrix][row][col];

prevCol = col;
prevRow = row;
prevMatrix = matrix;

index++;
col++;
if (col >= array3d[matrix][row].length) {
col = 0;
row++;
}
if (row >= array3d[matrix].length) {
row = 0;
matrix++;
}

if (element == null && this.hasNext()) {
return this.next();
}
return element;
}

@Override
public void remove() {
array3d[prevMatrix][prevRow][prevCol] = null;
}
}
17 changes: 17 additions & 0 deletions src/designpatterns/iterator/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package designpatterns.iterator;

public class Main {

public static void main(String[] args) {
Integer[][][] Array3d = {
{{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 4}, {null, null, null, null}},
{{9, 9, 9, 9}, {9, 9, 9, 9}, {9, 9, 9, 9}, {null, null, null, 8}},
{{8, 3, 5, 1}, {353, null}, {null, null, null, 12453}, {1, 2, 3, 4}}
};
Array3D<Integer> Iterable3dArray = new Array3D<>(Array3d);

while (Iterable3dArray.hasNext()) {
System.out.println(Iterable3dArray.next());
}
}
}