不定长参数方法

    说到不定长参数方法,其实有一个非常常用的方法,大家都用过的那就是main方法。下面就一起来看看不定长参数方法的demo;
   
package com;

public class UnfixedParameter {
	public static void main(String[] args) {
		testOne(new String[]{});
		testOne(new String[]{"a","b","c"});
		testTwo();
		testTwo("a","b","c");
	}
	
	public static void testOne(String[] args){
		for(String arg : args){
			System.out.println(arg);
		}		
	}
	
	public static void testTwo(String... args){
		for(String arg : args){
			System.out.println(arg);
		}
	}
}

    我们可以看出无论用String[]方式还是String...方式其实本质都是传入的一个字符串数组。这里还可以看出这种不定长参数方法的传参个数为>=0个。如果你希望必须传入一个或多个参数,那么可以在其前面添加参数(不能在后面添加,否则编译不通过),例如:
public static void test(int i,String par,String... args){}

    不定长参数方法方法重载:
   
package com;

public class UnfixedParameter {
	public static void main(String[] args) {
		test(new String[]{});
		test(new String[]{"a","b","c"});
		test();
		test("a","b","c");
	}
		
	public static void test(String... args){
		for(String arg : args){
			System.out.println(arg);
		}
	}
	
	public static void test(String par,String... args){
		System.out.println(par);
		for(String arg : args){
			System.out.println(arg);
		}
	}
}

    你一定会发现test("a","b","c")编译不通过。因为编译器无法确定你调用的是哪个方法。这里我故意给第一个方法传入的是String[]类型,上面我已经说过String[]和String...方式本质都是传入一个字符串数组,所以写成同名方法的话不叫方法重载,会导致编译报错。这里test(new String[]{})和test(new String[]{"a","b","c"})一定调用的是第一个方法,而test("a","b","c")无法确定调用的是哪个方法。因为你可以把第二个方法当成是传入一个字符串和一个字符串数组,也可以当成传入>=1个字符串。
    总结:
    1.两种方式本质都是传入的字符串数组,所以不能同时出现,否则编译无法通过
    2.String...参数必须放在最后面,否则编译无法通过
    3.第一种方式(即String[]方式)可以使用方法重载,第二种方式(即String...方式)使用方法重载时,调用方法时会编译不通过(参数个数为0个的时候除外)
    原文永久地址: http://jsonliangyoujun.iteye.com/blog/2364491

猜你喜欢

转载自jsonliangyoujun.iteye.com/blog/2364491
今日推荐