JDK 1.5开始,Java支持传递同类型的可变参数给一个方法。在方法声明中,在指定参数类型后加一个省略号(.…)。
package day13; public class Test03 { public static void main(String[] args) { Test03 test03 = new Test03(); test03.PrintMax(12.9, 9, 1, 33, 89.9); } public static void PrintMax(double... numbers) { if (numbers.length == 0) { System.out.println("no argument"); return; } double max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } System.out.println("最大值是:" + max); } }
执行结果:
"C:Program FilesJavajdk1.8.0_201injava.exe" "-javaagent:E:program filesIntelliJ IDEA Community Edition 2020.3.1libidea_rt.jar=62097:E:program filesIntelliJ IDEA Community Edition 2020.3.1in" -Dfile.encoding=UTF-8 -classpath "C:Program FilesJavajdk1.8.0_201jrelibcharsets.jar;C:Program FilesJavajdk1.8.0_201jrelibdeploy.jar;C:Program FilesJavajdk1.8.0_201jrelibextaccess-bridge-64.jar;C:Program FilesJavajdk1.8.0_201jrelibextcldrdata.jar;C:Program FilesJavajdk1.8.0_201jrelibextdnsns.jar;C:Program FilesJavajdk1.8.0_201jrelibextjaccess.jar;C:Program FilesJavajdk1.8.0_201jrelibextjfxrt.jar;C:Program FilesJavajdk1.8.0_201jrelibextlocaledata.jar;C:Program FilesJavajdk1.8.0_201jrelibext ashorn.jar;C:Program FilesJavajdk1.8.0_201jrelibextsunec.jar;C:Program FilesJavajdk1.8.0_201jrelibextsunjce_provider.jar;C:Program FilesJavajdk1.8.0_201jrelibextsunmscapi.jar;C:Program FilesJavajdk1.8.0_201jrelibextsunpkcs11.jar;C:Program FilesJavajdk1.8.0_201jrelibextzipfs.jar;C:Program FilesJavajdk1.8.0_201jrelibjavaws.jar;C:Program FilesJavajdk1.8.0_201jrelibjce.jar;C:Program FilesJavajdk1.8.0_201jrelibjfr.jar;C:Program FilesJavajdk1.8.0_201jrelibjfxswt.jar;C:Program FilesJavajdk1.8.0_201jrelibjsse.jar;C:Program FilesJavajdk1.8.0_201jrelibmanagement-agent.jar;C:Program FilesJavajdk1.8.0_201jrelibplugin.jar;C:Program FilesJavajdk1.8.0_201jrelib esources.jar;C:Program FilesJavajdk1.8.0_201jrelib t.jar;F:JavaCodecodeoutproductionasic" day13.Test03
最大值是:89.9
注意:一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通的参数必须在它之前声明。