Var-args
In Java, method specifications are pretty much set in stone. For example, a method that declares two parameters of a particular type must be called with those parameters. If you supply too many, too few, or incorrectly typed parameters, you will get a compile time error. Of course, we use method overloading to deal with the cases in which we need to declare a varying number or type of parameters.
However, every now and then it makes sense, or is more convenient, to have the one method handle any number of arguments that are thrown its way, just as you're allowed to do in languages like JavaScript and ColdFusion. The way many programmers previously simulated such behavior in Java was to create an array of parameters, then pass that array along as an argument to the desired method.
In Java 5, this rather messy approach is no longer necessary. Consider this method specification:
public void myMethod(Object … args)
Notice the three periods next to the parameter type? This is how we tell the method that it is allowed to accept a varying number of arguments. The type must be Object
, and it must be the last or only argument in the method specification. With that in mind, the following method calls are all perfectly legal:
myMethod(23, 34, 78);
myMethod("Hello", "Goodbye");
myMethod(123);
This makes sense, except for one thing. I said that the arguments must be of type Object
, yet I clearly pass along primitives in two of these calls! That's autoboxing in action -- the arguments are passed along as Object
types; the compiler takes care of the primitive wrapping on our behalf.
As you would expect, inside the method body, the parameters are handled as an array of type Object
. The following code sample shows how much code we may have needed to achieve the same thing prior to Java 5.
int num1 = 23;
int num2 = 28;
int num3 = 98;
Integer objNum1 = new Integer(num1);
Integer objNum2 = new Integer(num2);
Integer objNum3 = new Integer(num3);
Integer[] params = {objNum1, objNum1, objNum3}
myMethod(params);
Here, we do all the primitive wrapping ourselves. Then, we create the array-based parameter. Finally, we do the method call. Now that's a lot more work!
No comments:
Post a Comment