Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java varargs received in the same order in which they were given?

I can't find any documentation on this issue.

In some Lists and Maps, the order of the elements is random and is not the same order in which they were added to the list / map. Is that true about var args, or are they received in the same order in which they were sent?

E.g, I have a form validation method, which takes a field name and a vararg list of rules. If I supply the rules: Rules.INT, Rules.MAX.arg(100), then I would want the Rules.INT rule to be checked first, before the Rules.MAX rule is checked, because Rules.MAX assumes that the given value is a proper integer. Hence if Rules.INT fails, then Rules.MAX would not be called - however if the varargs are received in a random order, then Rules.MAX may get called before Rules.INT anyway, and could then throw up an exception if the value is not an integer, which is what I don't want.

Edit: Here's my method with the var args, for clarification:

public boolean validate(String name, Rule... rules)
{
   String value = getValue(name);
   for (Rule rule : rules)
   {
     if (! rule.match(value) )
        return false;
   }
   return true;
}

Now, if I called this method by: validate("age", Rule.INT, Rule.MAX.arg(100) ), can I be sure that Rule.INT will be iterated / checked before Rule.MAX in the validate() method?

like image 606
Ali Avatar asked Oct 13 '13 09:10

Ali


1 Answers

All method arguments are received in the order specified, whether varargs or otherwise. Under the hood, a varargs parameter is an array of the specified argument type, not a collection of any kind which could upset the order in the source text.

like image 191
user207421 Avatar answered Oct 06 '22 07:10

user207421