Tuesday, October 21, 2008

varargs in java 5

I'm going to talk about one of the minor enhancements of Java 5; Varargs. Normally, if you are going to pass an arbitrary number of elements (object or primitive type) to a function, you would put them into an array and then pass the array to the function.
Assuming we have a concat() function such as

String concat(String[] tokens){
String result = "";
for(int i=0; i<tokens.length; i++){
result += tokens[i];
}
return result;
}

We will put all the Strings to be concatanated in an array and pass them to concat(). i.e. concat( new String[]{"come", "on", "eileen"} ) .

With Varargs, it is now possible to skip the array creation and pass the elements (again, object or primitive type) directly to the method. You change the concat() function so that it can accept them. String concat(String[] tokens){ becomes String concat(String... tokens){ and now you're free to pass any number of elements to concat() function without worrying about an array.
i.e. concat("come", "on", "eileen"); concat("dexymidnightrunners");

No comments:

Post a Comment