Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package esercizio3.iterable;
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- /**
- * Created by stefano on 12/01/16.
- */
- public class IterableMatrix implements Iterable<Integer> {
- public final int[][] mat;
- public IterableMatrix(int[][] m) {
- if (m.length > 0) {
- this.mat = new int[m.length][m[0].length];
- } else this.mat = new int[0][0];
- for (int i = 0; i < mat.length; i++) {
- for (int j = 0; j < mat[0].length; j++) {
- mat[i][j] = m[i][j];
- }
- }
- }
- public IterableMatrix(int r, int c) {
- mat = new int[r][c];
- }
- public static void main(String[] args) {
- int[][] m = new int[][]{
- {},
- };
- IterableMatrix im = new IterableMatrix(m);
- for (Integer v : im) {
- System.out.println(v);
- }
- }
- @Override
- public Iterator<Integer> iterator() {
- return new MYit();
- }
- private int getRowCount() {
- return mat.length;
- }
- private int getColumnCount() {
- if (mat.length > 0)
- return mat[0].length;
- else return 0;
- }
- private class MYit implements Iterator<Integer> {
- int r, c;
- public MYit() {
- r = 0;
- c = 0;
- }
- @Override
- public boolean hasNext() {
- return r < getRowCount() && c < getColumnCount();
- }
- @Override
- public Integer next() {
- if (!hasNext())
- throw new NoSuchElementException();
- final int vale = mat[r][c];
- c++;
- if (c >= getColumnCount()) {
- c = 0;
- r++;
- }
- return vale;
- }
- @Override
- public void remove() {
- throw new UnsupportedOperationException("remove");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement