可变参数重载的问题

1. 可变参数相当于传数组参数,参数为0相当于数组为空

2. 当可变参数方法重载的时候,如果实际传参为0个,编译将不通过(无法分辨调用的哪个方法)

package com.yjq.cn.initialize;

/**
 *  可变参数
 */
public class VarArgsTest {
	
	static void fc(int i, String... str) {
		System.out.print("fc.args : [" + i + " ");
		for(String s : str) {
			System.out.print(s + " ");
		}
		System.out.println("]; args.length: " + str.length);
		
	}

	//重载1
	static void f(Integer... args) {
		System.out.print("first");
		for(Integer i : args) {
			System.out.print(" " + i);
		}
		System.out.println();
	}
	//重载2
	static void f(Character... args) {
		System.out.print("second");
		for(Character c : args) {
			System.out.print(" " + c);
		}
		System.out.println();
	}
	//重载3
	static void f(Long... args) {
		System.out.print("third");
		for(Long l : args) {
			System.out.print(" " + l);
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		fc(1, "one");
		fc(2, "two", "three");
		//可变参数个数可以传0个
		fc(0);
		
		System.out.println("--------------------");
		
		//重载的情况
		f('a', 'b', 'c');
		f(1);
		f(2, 1);
		f(0);
		f(0L);
//		f();  //此时编译报错 The method f(Integer[]) is ambiguous for the type VarArgsTest
	}
	
}

//output

fc.args : [1 one ]; args.length: 1 fc.args : [2 two three ]; args.length: 2 fc.args : [0 ]; args.length: 0 -------------------- second a b c first 1 first 2 1 first 0 third 0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值