在Java1.5中创建可变参数[Varargs] (1)
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) {
}
这段代码调用了Guitar类中三个版本的构造器,意味着当信息可见时,这些信息会被支持,而不是迫使每一个使用者每一次都要去了解关于Guitar类的所有知识。许多专家不会在关键时候告诉你他们的Guitar的内容。下面是用到的构造器:
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) {
}
然而,当你想要去增加无限的信息时,事情开始变得有一点不是那么有用了。例如:假设你想允许在这个构造器中增加额外的未指明的特性。下面就是一些可能的调用的例子:
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");
对于这两个单独的情况,你不得不去增加一个构造器来接受两个额外的字符串,另外一个构造器来接受四个额外的字符串。试图将这些相似的版本应用于早已重载的构造器。根据这样的话,你最终会得到20或30个那样愚蠢的构造器的版本!
原因在于我们常称做的可变参数。可变参数是Tiger的增加的另一个特性,它用一种相当巧妙的方法彻底地解决了这儿提出的问题。这一章讲述了这种相对简单的特性的各个方面。这将会使你迅速写出更好、更整洁、更灵活的代码。
创建一个可变长度的参数列表
可变参数使得你可以指定某方法来接受多个同一类型的参数,而且并不要求事先确定参数的数量(在编译或运行时)。
这就是Tiger的一个集成部分。事实上,正是因为Java语言的一些新特性组合在一起才表现出了可变参数的特性。


您的位置:
