Creating a Variable-Length Argument List
Iterating Over Variable-Argument Lists
Allowing Zero-Length Argument Lists
Specify Object Arguments Over Primitives
Avoiding Automatic Array Conversion
One of the coolest features of Java, and of any object-oriented language, is method overloading. While many might think Java's strengths are its typing, or all the fringe APIs it comes with, there's just something nice about having the same method name with a variety of acceptable arguments:
Guitar guitar = new Guitar("Bourgeois", "Country Boy Deluxe", GuitarWood.MAHOGANY, GuitarWood.ADIRONDACK, 1.718); Guitar guitar = new Guitar("Martin", "HD-28"); Guitar guitar = new Guitar("Collings", "CW-28" GuitarWood.BRAZILIAN_ROSEWOOD, GuitarWood.ADIRONDACK, 1.718, GuitarInlay.NO_INLAY, GuitarInlay.NO_INLAY);
This code calls three versions of the constructor of a (fictional) Guitar class, meaning that information can be supplied when it's available, rather than forcing a user to know everything about their guitar at one time (many professionals couldn't tell you their guitar's width at the nut). Here are the constructors used:
public Guitar(String builder, String model) { } public Guitar(String builder, String model, GuitarWood backSidesWood, GuitarWood topWood, float nutWidth) { } public Guitar(String builder, String model, GuitarWood backSidesWood, GuitarWood topWood, float nutWidth, GuitarInlay fretboardInlay, GuitarInlay topInlay) { }
However, things start to get a little less useful when you want to add information that isn't finite. For example, suppose you want to allow additional, unspecified features to be added to this constructor. Here are some possible invocation examples:
Guitar guitar = new Guitar("Collings", "CW-28" GuitarWood.BRAZILIAN_ROSEWOOD, GuitarWood.ADIRONDACK, 1.718, GuitarInlay.NO_INLAY, GuitarInlay.NO_INLAY, "Enlarged Soundhole", "No Popsicle Brace"); Guitar guitar = new Guitar("Martin", "HD-28V", "Hot-rodded by Dan Lashbrook", "Fossil Ivory Nut", "Fossil Ivory Saddle", "Low-profile bridge pins");
For these two cases alone, you'd have to add another constructor that takes two additional strings, and yet another that takes four additional strings. Try and apply these same versions to the already-overloaded constructor, and you'd end up with 20 or 30 versions of that silly constructor!
It's here where variable arguments, more often called varargs, come in. Another of Tiger's additions, varargs solve the problem detailed here once and for all, in a pretty slick way. This chapter covers this relatively simple feature in all its glory, and will have you writing better, cleaner, more flexible code in no time.
Chapter 9, use varargs.