Java可变参数

本文详细介绍了Java中可变参数(varargs)的使用方法及其限制条件。通过具体实例展示了如何定义和调用带有可变参数的方法,并解释了可变参数与数组之间的区别和联系。

java不定参数(可变参数)

package variableParams;

public class VariableParams {

	public static void main(String[] args) {

		method(1);
		method();
		method(1,2,3,4,5,6);//可以直接写参数
		int[] a = {1, 2, 3, 4, 5, 6, 7};
		method(a);//可以传数组
		
		
	}
	
	public static void method(int... args) {
		//不定参数本质上是一个数组,可以调用数组方法
		int length = args.length;
		System.out.println("------>不定参数方法正在运行<-------");
		int i = 0;
		for (int e : args) {
			i++;
		}
		System.out.println("参数长度为:" + length);
		System.out.println("参数个数为:" + i);
	}
	
	public static void method(int i) {
		System.out.println("------>单个参数方法正在运行<-------");
	}
	
	public static void method(int i, int j) {
		System.out.println("------>两个参数方法正在运行<-------");
	}
	public static void method1(int[] arr) {
		System.out.println("......");
	}

	
//	public static void method(int[] args) {
//		//编译时报Duplicate method method(int[]) in type VariableParams,
//		//不能使用数组实现不定参数方法重载,不定参数本质上是一个数组
//		
//	}
	
//	public static void method(int i, int...args) {
//		//编译时时报The method method(int[]) is ambiguous for the type VariableParams
//		//务必保证参数列表不一致
//	}
//	private static void method(int... args,int... params) {
//		//编译时报The variable argument type int of the method method must be the last parameter
//		// 不定参数项只能在最后,所以只能有一个
//
//	}

	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值