Exercise 2.10: Add a toString method to Vehicle.
Exercise 2.11: Add a toString method to LinkedList.
2.6.3. Methods with Variable Numbers of Arguments
The last parameter in a method (or constructor) parameter list can be declared as a sequence of a given type.
To indicate that a parameter is a sequence you write an ellipse (...) after the parameter type, but before its
name. For example, in
public static void print(String... messages) {
// ...
}
the parameter messages is declared to be a sequence of String objects. Sequence parameters allow a
method to be invoked with a variable number of arguments (including zero) that form the sequence. Such
methods are known as variable-argument, or more commonly varargs methods; methods that don't declare a
sequence parameter are known as fixed-argument methods.[2]
[2] More formally, the number of arguments that can be passed to a method invocation is
known as the arity of the invocation. Varargs methods are variable-arity methods, while
fixed-argument methods are fixed-arity methods.
The need to process a variable number of arguments can arise in many situations. For example, our Body
objects already track which other body they orbit, but it can be useful to know which Body objects they are
orbited by. While a given body generally only orbits one other body, it may itself be orbited by many other
bodies. To track this we could define an array of Body objects and provide a method to add each orbiting
body, one at a time, to that array. That is not an unreasonable solution, but it is much more convenient if we
just define a method that can take a sequence of Body objects:
public void setOrbiters(Body... bodies) {
// ... store the values ...
}
You could then use this method in the following way:
Body sun = new Body("Sol", null);
Body earth = new Body("Earth", sun);
Body moon = new Body("Moon", earth);
Body mars = new Body("Mars", sun);
Body phobos = new Body("Phobos", mars);
Body deimos = new Body("Deimos", mars);
earth.setOrbiters(moon);
mars.setOrbiters(phobos, deimos);
You may be wondering what type the parameter sequence bodies has inside setOrbitersquite simply it
is an array of Body objects. Declaring a parameter as a sequence is nothing more than asking the compiler to
construct an array for you and to set its elements to be the arguments actually passed for the sequence. When