Java中的三个点"..."

转自:https://blog.csdn.net/it_faquir/article/details/49131173
 java1.5引入。"…"必须是方法的最后一个形参,表示多个(0,1,2,…)参数,类似数组参数,使用数组传实参
但是与数组参数又有区别,"…"表示可变长参数(多个参数),数组参数只是一个参数。详见下面举例:

public class Test {
	void t1(String... a) {
		System.out.println("t1");
		for (String s : a)
			System.out.printf(" " + s);
		System.out.println();
	}
 
	void t2(String[] a) {
		System.out.println("t2");
		for (String s : a)
			System.out.printf(" " + s);
		System.out.println();
	}
 
	public static void main(String[] args) {
		String a[] = { "a", "b", "d", "e", "f", "g" };
		Test t = new Test();
		t.t1(a);
		t.t2(a);
		// 区别
		t.t1();// 可不传
		// t.t2();//必须传参数,否则报错
		t.t1("1", "2", "3", "4");// 也可以一个一个的传,t2则不可以
	}
}

运行结果:

t1
 a b d e f g
t2
 a b d e f g
t1

t1
 1 2 3 4

猜你喜欢

转载自blog.csdn.net/DavidHuang2017/article/details/85269770