Home > Enterprise >  How can I create a method in Java to create a new loop type?
How can I create a method in Java to create a new loop type?

Time:02-22

I'm working on creating some Java methods to make writing code quicker and more efficient, and right now I'm trying to make a simple loop I'm calling "repeat."

It will work something like this:

repeat(number of times to repeat) {
   code to be repeated
}

So for example:

repeat(3) {
   System.out.println("hi")
}

Would display:

hi
hi
hi

How can I make a method/function like this? I also need it to work as a nested loop.

CodePudding user response:

repeat(3) {
   System.out.println("hi")
}
  1. java not support the grammer, if you want the grammer may try other language support closure
  2. but another way you cay try, java can implement it by lambda
public static void main(String[] args) {

   repeat(3, () -> {
       System.out.println("hi");
   });
}

public static void repeat(int count, Runnable function) {
   for(int i = 0; i < count; i  ) {
      function.run();
   }
}

CodePudding user response:

If you really wanted to avoid all for loops you could use a recursive version of @math-chen's solution:

public static void repeat(int count, Runnable function) {
        if (count > 0) {
           function.run();
           repeat(count - 1, function);
        }
}

As the recursive call is at the end of the method, this "tail-call" can in theory be optimised to not use any extra stack, but the JVM may not do that. (And experiment shows that it doesn't)

  • Related