Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How can I pass a generic java function as a parameter?

Asked by Manish Jhadav Oct 11, 2022 1.3K views 1 answer
Share

About this question

Ran into this idea and I'm curious if it's possible.

I'm trying to make a single function that can test ALL of my sorting algorithms dynamically. I want to be able to pass the sorting function as a parameter and the algorithm will use the sorting function with its own dynamic parameters. This is an example of what I'm trying to do:

class manyFunctions{
    int[] mergeSort(int[] myArray){
        ...work here;
        return sortedArray;
    }
    int[] otherSort(int[] myArray){
        ...work here;
        return sortedArray;
        }
}
class mainClass{
   public static void main(String[]Args){
      test(manyFunctions.mergeSort);
      test(manyFunctions.otherSort);
   }
 boolean test(function someSortFunction){
        int n; // number of trials
        for (int i=0; i<=n ; i++) {
        int[] A = generateArray() // another function I made
            if (isSorted(someSortFunction(A)) = false) {
                return false;
            }
        }
     return true;
 }

I can't figure out how to do this with the little bit I know about lambda expressions and function pointers. If it's possible, this technique would come in handy.


Your answer

1 Answer

More Java discussions