Java Collections Framework - Overview and use variable parameters

Overview of variable parameters

 
  • The method defined time do not know how many parameters defined
 

format

 
  • Modifier return type method name (variable name data type ...)} {
  • note:
variable here is actually an array
If a method with a variable parameter, and there are a number of parameters, then the variable parameters must be the last one
 
 

 The following code demonstrates:

package cn.wen_01;
			
public class ArgsDemo {
	public static void main(String[] args) {
		// 2个数据求和
		int a = 10;
		int b = 20;
		int result = sum(a, b);
		System.out.println("result:" + result); //30

		// 3个数据的求和
		int c = 30;
		result = sum(a, b, c);
		System.out.println("result:" + result); //60

		// 4个数据的求和
		int d = 30;
		result = sum(a, b, c, d);
		System.out.println("result:" + result); //90

		// 需求:我要写一个求和的功能,到底是几个数据求和呢,我不太清楚,但是我知道在调用的时候我肯定就知道了
		// 为了解决这个问题,Java就提供了一个东西:可变参数
		result = sum(a, b, c, d, 40);
		System.out.println("result:" + result); //0

		result = sum(a, b, c, d, 40, 50);
		System.out.println("result:" + result); //0
	}
	
         public static int sum(int a, int b, int c, int d) {
	     return a + b + c + d;
	 }
	
	 public static int sum(int a, int b, int c) {
	     return a + b + c;
	 }
	
	 public static int sum(int a, int b) {
	     return a + b;
	 }
}

 Introducing variable parameters, code testing as follows:

package cn.wen_02;
				
public class ArgsDemo {
	public static void main(String[] args) {
		// 2个数据求和
		int a = 10;
		int b = 20;
		int result = sum(a, b);	
		System.out.println("result:" + result); //0

		// 3个数据的求和
		int c = 30;
		result = sum(a, b, c);
		System.out.println("result:" + result); //0

		// 4个数据的求和
		int d = 30;
		result = sum(a, b, c, d);
		System.out.println("result:" + result); //0

		// 需求:我要写一个求和的功能,到底是几个数据求和呢,我不太清楚,但是我知道在调用的时候我肯定就知道了
		// 为了解决这个问题,Java就提供了一个东西:可变参数
		result = sum(a, b, c, d, 40);
		System.out.println("result:" + result); //0

		result = sum(a, b, c, d, 40, 50);
		System.out.println("result:" + result); //0
	}

	public static int sum(int... a) {
		return 0; 
	}

	public static int sum(int a, int b, int c, int d) {
		return a + b + c + d;
	 }
	
	 public static int sum(int a, int b, int c) {
		return a + b + c;
	}
	
	 public static int sum(int a, int b) {
		return a + b;
	 }
}
 
 
 
Published 91 original articles · won praise 16 · views 1164

Guess you like

Origin blog.csdn.net/hewenqing1/article/details/104102960