Functions with variable number of input arguments in Java

static public final float myMax(float... input) {
    -- code for finding max of an array --
}

Java automatically transforms your input into an array which you can traverse like an array.
This means that you only need to define a single function and it will be able to deal with all of these scenarios

myMax(1,2);
myMax(1,2,-1,2,20000000,9,3); 
myMax(new float[]{1,2,-1,2,20000000,9,3});

You’re not constrained to just the float type though. Any class will do, from Strings, to booleans, to custom classes you’ve created yourself.

Wish I’d known this when I first began using Java.

Advertisements