J2SE 5.0 (Tiger)的发布是Java语言发展史上的一个重要的里程碑, 是迄今为止在 Java 编程方面所取得的最大进步。
J2SE 5.0提供了很多令人激动的特性.这些特性包括范型(generics)的支持, 枚举类型(enumeration)的支持, 元数据(metadata)的支持, 自动拆箱(unboxing)/装箱(autoboxing), 可变个数参数(varargs), 静态导入(static imports), 以及新的线程架构(Thread framework)。
Tiger引入了可变参数这一概念,一个方法可以使用不定数量的同一个类型的变量。首先在方法的变量生命中使用(...)来声明可变参数。例如:
类Guitar的一个构造方法形如:
public Guitar(String builder, String model, String... features);
因此方法里边有String...features这个可变的参数声明,下面构造的Guitar对象都是合法的:
Guitar guitar = new Guitar("Martin", "HD-28V",
"Hot-rodded by Dan Lashbrook", "Fossil Ivory Nut",
"Fossil Ivory Saddle", "Low-profile bridge pins");
Guitar guitar = new Guitar("Bourgeois", "OMC",
"Incredible flamed maple bindings on this one.");
Guitar guitar = new Guitar("Collings", "OM-42",
"Once owned by Steve Kaufman--one of a kind");
这就为我们构造不同的对象创造了更灵活的方法!
下面举一个例子:
/**
* Copyright (C) 2005
* All right reserved
* @author Jekey XJTU
* 文件Test05.java创建于 Aug 18, 2005 11:48:07 PM
*/
package cn.edu.xjtu.jekey;
public class Test05 {
public static void main(String[] args) {
String[] names = {"Jekey","sawpad","lopp"};
int result = max(1, 2, -1,3, 4, 5, 2, 3,18, 6, 7);
System.out.println("result=" + result);
printString(names);
Object[] obj = new
Strin[]{"Hello", "to", "all", "of", "you"};
System.out.printf("Description of object array: %s %s\n", obj);
//此处测试了方法PrintStream printf(String format, Object... args);
System.out.printf("Description of object array: %s\n", (Object)obj);
}
public static int max(int... values) {
if (values.length == 0) {
throw
new IllegalArgumentException("No values supplied.");
}
int max = Integer.MIN_VALUE;
for (int i : values) {
if (i > max)
max = i;
}
return max;
}
public static void printString(String... Names) {
for (String name : Names) {
System.out.println("name: " + name);
}
}
}
程序运行结果:
result=18
name: Jekey
name: sawpad
name: lopp
Description of object array: Hello to
Description of object array: [Ljava.lang.String;@190d11