java – Should I use the iterator pattern?


Good day.

The question is: there is a two-dimensional array of objects. Several modules in the program regularly request some part of this array and sequentially iterate over its elements. For some modules, the traversal order is not important, but for some it is critical. So, for example, one module asks for a "rectangular" piece of this two-dimensional array and it needs to go through each line twice, starting from the top. So, is it appropriate to use the iterator pattern if the traversal order is critically important for its clients and each client may need to set its own traversal order, while implementing several iterators with different interfaces? And if not, please tell me, is it worth then to transfer the two-dimensional array to clients directly, taking into account that it may be necessary to change the way of storing data? What is the best architectural solution in this case?


General recommendations

It is worth making either one class with several methods that provide selections, or several classes, one per selection type, and distribute them to consumers.

Each fetch method must return a specialized iterator. But the interfaces for iterators will be the same: this is the usual Java Iterator interface.

Regarding fetching a rectangular area and double iterating over rows:

It is worth doing this: the selection method returns an iterator over objects of the Row type (add your own prefix), which implements the Iterable interface. Each such object has a reference to a data string and fields first and length , and from it you can get an iterator over such a "slice". This way you can iterate over both lines and elements:

Iterable<RectRow> rows = someQuerier.getRect(left, top, width, height);
for (RectRow row : rows) {
    // многократный проход по одной и той же строке
    for (int rowPassCount = 0; rowPassCount < maxRowPassCount; rowPassCount += 1) {
        for (YourItem item : row) {
            // Ваши действия с элементом
Scroll to Top