Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring at least one element in java variable argument list

In this code construct:

public MyClass(Integer... numbers) {     do_something_with(numbers[]); } 

is it possible to require that numbers contains at least one entry in such a way, that this is checked at compile-time? (At run-time, of course, I can just check numbers.length.)

Clearly I could do this:

public MyClass(Integer number, Integer... more_numbers) {     do_something_with(number, more_numbers[]); } 

but this isn't going to be very elegant.

The reason I would like to do this is to make sure that a sub-class does not simply forget to call this constructor at all, which will default to a call to super() with no numbers in the list. In this case, I would rather like to get the familiar error message: Implicit super constructor is undefined. Must explicitly invoke another constructor.

Could there be another way to achieve the same, like some @-annotation that marks this constructor as non-implicit?

like image 361
Markus A. Avatar asked Oct 05 '12 18:10

Markus A.


People also ask

What is variable arguments in Java?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }

How do you pass multiple arguments in Java?

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

What is variable argument and what rules are defined for variable argument?

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.

How many maximum numbers of Varargs or variable arguments can be there in a method or a constructor in Java?

13) How many maximum numbers of Varargs or Variable-Arguments can be there in a method or a constructor in Java? Explanation: Yes, only one.


1 Answers

I think the best approach to have at least 1 argument is to add one like this:

public MyClass (int num, int... nums) {     //Handle num and nums separately     int total = num;     for(i=0;i<nums.length;i++) {         total += nums[i];     }     //... } 

Adding an argument of the same type along with varargs will force the constructor to require it (at least one argument). You then just need to handle your first argument separately.

like image 111
Ivan V Avatar answered Sep 28 '22 04:09

Ivan V