Sequentially accepting elements from a two-dimensional array (Java)

I am new to Java and I need to write a method next()that will return the current value from a 2D array.

For example, we can have:

int[][] values = {{1, 2}, {3, 4}, {5, 6}}; 

When we use it next()for the first time, it returns 1, the second - 2, the third - 3etc.

My solution is to make a 1D array from this 2D array:

 public int[] convert(int[][] array) {

        // At first, count number of all cells to set length for new 1D array.

        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                count++;
            }
        }

        // Now we have length. Creating new array and filling it with data from all arrays.

        int[] result = new int[count];
        int index = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                result[index] = array[i][j];
                index++;
            }
        }
        return result;
    }

And then just get the value from this new 1D array ( position- this is a class field = 0, valuesalso a class field - int[][] values):

public int next() {
        int[] tmp = convert(values);
        int result = tmp[position];
        position++;
        return result;
    }

But it is obvious that this solution is not the best. Is there any way to do this without talking to arrays?

Something similar to Iterator next()and hasNext()?

. , , :

public class ArrayConverter {
    private final int[][] values;
    private int upper = 0;
    private int lower = -1;

    public ArrayConverter(int[][] values) {
        this.values = values;
    }

    public int next() {
        lower++;
        int result = 0;
        try {
            result = values[upper][lower];
        } catch (ArrayIndexOutOfBoundsException a) {
            lower = 0;
            upper++;
            try {
                result = values[upper][lower];
            } catch (ArrayIndexOutOfBoundsException r) {
                upper = 0;
                lower = -1;
                System.out.print("Reached the end of data. Indexes will be zeroed.");
            }
        }
        return result;
    }
}

- try/catch, . ?

+4
2

List, :

int[][] array = {{1, 2}, {3, 4}, {5, 6}}; 
List<Integer> list = new ArrayList<>();
for (int[] array1 : array) {
    for (int j = 0; j < array1.length; j++) {
        list.add(array1[j]);
    }
}

list.get(position);

+3

. Stream API :

OfInt iter = Stream.of(a).flatMapToInt(IntStream::of).iterator();

while (iter.hasNext()) {
    iter.nextInt();
}
0

Source: https://habr.com/ru/post/1668439/


All Articles