java不定长参数的简单使用

      今天学习了thinking in java ,看了不定长的参数,记录下来以备用到时候找不到,以下是string类型的,其他类型的一样

public class OptionalTrailingArguments {
	static void f(int required, String... trailing) {
		System.out.print("required: " + required + " ");
		System.out.println(trailing.length);
		
	}

	public static void main(String[] args) {
		f(1, "one");
		f(2, "two", "three");
		f(0);
	}
}

 

有时会对方法重载,注意下面的用法,有时候可能会带来意想不到的错误

public class VariArgs {

	public static void main(String[] args) {
		test();
		test("aaa");
		test("aaa", "bbb");
		test("aaa", "bbb", "ccc");
	}

	public static void test(String... args) {
		System.out.println(args.getClass());
		for (String arg : args) {
			System.out.println(arg);
		}
	}

	public static void test(String arg, String... args) {
		System.out.println(arg);
		System.out.println("----------------");
		for (String s : args) {
			System.out.println(s);
		}
	}
}


 

 

你可能感兴趣的:(java,String,Class)