-2

I have a lot of functions and want to use an array to call them. I know how to do it in c++ but dont know how to do it in java. Pseudocode of my intention bellow:

Array<function pointers> functionBook[100];
functionBook.add(function_0);
functionBook.add(function_1);
 .
 .
 .
functionBook.add(function_99);


void functionCaller(int i){
  functionBook[i](); // will call function_i()
}
Kirk
  • 15
  • 1
  • 2

1 Answers1

3

Try using lambdas and functional interfaces:

public static void main(String[] args) {

    List<Runnable> list = List.of(
            () -> System.out.println("first"),
            () -> System.out.println("second"),
            () -> System.out.println("third")
    );

    list.forEach(Runnable::run);

}

You can use any other interfaces, like Function<R, T> that can accept values, or create your own functional interface.

Backflip
  • 232
  • 2
  • 9