Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Also download the lecture notes on this subject that includes an interesting decomposition of the Quicksort problem into an architecture that can be efficiently run in parallel on multi-core processors.

===================================================================================================================

Variable Argument Lists

We discussed this before in lab and lecture, but it's worth revisiting to make sure everyone understands it.

A parameter defined as "P... params" is a vararg input parameter of type P.    A vararg input parameter allows you to call the method with zero, one, two, or however many values as you want.

For instance, suppose I have a method define as such:

Code Block

// returns the sum of all the input values supplied
int sum(int...params) {
   int result = 0;
   for(int i=0; i< params.length; i++) {
       result += params[i];
   }
   return result;
}


(Note: there are more efficient ways of writing this method, but I wanted to show you several features at once)

Wiki Markup
A vararg parameter comes in as an array, so one can figure out how many parameters were supplied (params.length) and one can access each supplied value using regular array syntax, e.g. params\[i\].
\\

The following are all valid calls to the above method:

...


sum()  --> returns zero.

sum(42)  --> returns 0+42 = 42.

sum(10, 20)  --> returns 0+10+20 = 30.

sum(100, 1000, 10000)  --> returns 11100 etc

Vararg input parameters are very useful when you might want to call a method, such as the accept method of a host (and hence a case on the visitor), with varying numbers of input parameters, or perhaps, none at all.

If you don't need to use the input parameter, I suggest using the "Void" object type and calling your parameter something like "nu" (for "not used"):

Void... nu

When you call the visitor, simply don't supply an input parameter.  

If you need an input parameter, just set the P to the type you need and call the accept method with as many values as you need.   Note that the one restriction of a vararg input parameter is that all the input values have to be of the same type.

The visitor system that HW11 uses allows you to give parameters to the visitor at the time that you use the visitor rather than having to imbed additional parameters inside the visitor as was done in many examples in class.   This means that the same visitor instance can be used in multiple situations with different input parameters.   To note however, when using anonymous inner classes, input parameter values are often not needed because the anonymous inner class already has access, via its closure, to most of the values it needs.    Input parameters are particularly useful for things such as accumulators however, which cannot be curried in.

...