赞
踩
package com.google.varargs; import java.io.*; /** * @author : ♞Demons♛ * @date : 2020-01-05 13:31 * Description : java中的可变参数 **/ public class TestVarargs { public static void main(String[] args) throws Exception { // 测试int类型 varArgsInt(1); varArgsInt(2, 3); varArgsInt(4, 5, 6); // 测试字符串类型 varArgsString("A"); varArgsString("B", "C"); varArgsString("D", "E", "F"); // 测试入参int类型 printVarArgsInt(1); printVarArgsInt(1, 2, 3); // 测试入参字符串类型 printVarArgsString("A"); printVarArgsString("A", "B", "C"); // 测试可变参数的位置 varArgsLocation(1, "A", "B", "C"); // 测试实现相同接口的类的可变参数用法 varArgsAutoCloseable( new FileInputStream(new File("D://text.txt")), new OutputStreamWriter(new OutputStream() { @Override public void write(int b) throws IOException { System.out.println("for test, do nothing!"); } })); } private static void varArgsInt(int...numbers) { for (int number : numbers) { System.out.println("number:" + number); } } private static void varArgsString(String...strings) { for (String string : strings) { System.out.println("string:" + string); } } private static void printVarArgsInt(int...numbers) { for (int number : numbers) { System.out.println("print number:" + number); } } private static void printVarArgsString(String...strings) { for (String string : strings) { System.out.println("print string:" + string); } } private static void varArgsLocation(int number, String...strings) { System.out.println("可变参数必须是入参的最后位置"); for (String string : strings) { System.out.println("string location:" + string + "-" + number); } } private static void varArgsAutoCloseable(AutoCloseable...autoCloseables) throws Exception { for (AutoCloseable autoCloseable : autoCloseables) { autoCloseable.close(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。