Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing a loop using final variables

Is there a way to implement a loop using final variables? I mean a loop that would run for a specified number of iterations when you are not allowed to change anything after initialization!

like image 889
Zahra Avatar asked Mar 05 '26 20:03

Zahra


2 Answers

Is recursion allowed, or do you literally need a loop construct like for or while? If you can use recursion, then:

void loop(final int n) {
  if (n == 0) {
    return;
  } else {
    System.out.println("Count: " + n);
    loop(n-1);
  }
}
like image 117
jacobm Avatar answered Mar 07 '26 10:03

jacobm


One way is to create an Iterable<Integer> class representing an arbitrary range (without actually having to store all of the values in a list):

public static class FixedIntRange implements Iterable<Integer> {
    private final int min;
    private final int max;

    public FixedIntRange(final int min, final int max) {
        this.min = min;
        this.max = max;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            private Integer next = FixedIntRange.this.min;

            @Override
            public boolean hasNext() {
                return next != null;
            }

            @Override
            public Integer next() {
                final Integer ret = next;
                next = ret == max ? null : next + 1;
                return ret;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
}

and then iterate over it normally:

for (final int i : new FixedIntRange(-10, 20)) {
    // this will be run for each i in the range [-10, 20]
}
like image 23
ruakh Avatar answered Mar 07 '26 10:03

ruakh