Saturday, 10 June 2017

java - Passing Multiple Numbers in a Parameter for an Array



Is it possible to pass multiple numbers as a parameter for an array parameter? Just like I would with a regular int. Or does the parameter have to be a separate array that I have to create?



public static void main(String[] args)
{



getIntegers(1,2,3,4,5);



}



public static void getIntegers(int[] array)
{



//write whatever here



}

Answer




You can use varargs.



public static void getIntegers(int... array)


It can be referenced as an int[] from within the method body.



The method can be invoked by passing any given number of ints, or null.



Also note





  • You cannot declare more than one varargs per method signature.

  • If you intend to declare more than one parameter in your method, the varargs must be the last one


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...