Home  >  Article  >  Java  >  Detailed explanation of variable length parameter code in Java

Detailed explanation of variable length parameter code in Java

小云云
小云云Original
2017-12-06 09:38:261428browse

Up to J2SE1.4, it has been impossible to define a method with a variable number of actual parameters in a Java program - because Java requires that the number and type of actual parameters (Arguments) and formal parameters (Parameters) must match one by one, and The number of formal parameters is fixed when the method is defined. Although it is possible to provide versions with different numbers of formal parameters for the same method through the overloading mechanism, this still cannot achieve the purpose of allowing the actual parameter quantities to change arbitrarily.

However, the semantics of some methods require that they must be able to accept a variable number of actual parameters - for example, the famous main method needs to be able to accept all command line parameters as actual parameters, and the command The number of row parameters cannot be determined in advance.

For this problem, traditionally the approach of "using an array to wrap the actual parameters to be passed" is used to deal with this problem. This article mainly introduces the detailed explanation of variable length parameter code in Java, involving several issues such as the definition method of variable number of actual parameters, array wrapping of actual parameters, etc. It has certain reference value and friends in need can learn about it.

1. Wrap actual parameters with arrays

The method of "wrapping actual parameters with arrays" can be divided into three steps: First, for this method Define an array parameter; then when calling, generate an array containing all the actual parameters to be passed; finally, pass this array as an actual parameter.

This approach can effectively achieve the purpose of "allowing the method to accept a variable number of parameters", but the form of the call is not simple enough.

J2SE1.5 provides the Varargs mechanism, allowing you to directly define formal parameters that can match multiple actual parameters. Thus, a variable number of actual parameters can be passed in a simpler way.

The meaning of Varargs

Generally speaking, "Varargs" means "variablenumberofarguments". Sometimes they are simply called "variablearguments", but because this name does not explain what is variable, the meaning is a little vague.

2. Define a method with a variable number of actual parameters

As long as the "type" and "parameter name" of a formal parameter By adding three consecutive "." (that is, "...", the ellipsis in the sentence in English), you can match it with uncertain actual parameters. A method with such formal parameters is a method with a variable number of actual parameters.

Listing 1: A method with a variable number of actual parameters


private static int sumUp(int... values) {
}


Note that there is only the last formal parameter A talent can be defined as one that "can match an unspecified number of actual parameters". Therefore, there can only be one such parameter in a method. In addition, if this method has other formal parameters, put them in the front position.

The compiler will secretly convert this last formal parameter into an array parameter, and put a mark in the compiled class file to indicate that this is a method with a variable number of actual parameters.

Listing 2: The secret form of a method with a variable number of actual parameters


private static int sumUp(int[] values) {
}


Because there is such a Conversion, so you can no longer define a method for this class with the same signature as the converted method.

Listing 3: Combinations that will cause compilation errors


private static int sumUp(int... values) {
}
private static int sumUp(int[] values) {
}


3. Call the implementation Method with a variable number of parameters

As long as you write the actual parameters to be passed to the corresponding positions one by one, you can call a method with a variable number of actual parameters. No other steps are required.

Listing 4: Several actual parameters can be passed

sumUp(1,3,5,7);

Behind the scenes, the compiler This kind of calling process will be converted into the form of "wrapping actual parameters with an array":

Listing 5: Secretly appearing array creation

sumUp(newint[]{1,2 ,3,4});

In addition, the "uncertain number" mentioned here also includes zero, so such a call is also reasonable:

Listing 6: Also You can pass zero actual parameters

sumUp();

The effect of this calling method after being secretly converted by the compiler is equivalent to this:

List 7: Zero actual parameters correspond to empty array

sumUp(newint[]{});

Note that an empty array is passed at this time, and Not null. In this way, it can be handled in a unified form without having to detect which situation it belongs to.

4. Processing a variable number of actual parameters

Methods for processing a variable number of actual parameters, and processing array actual parameters The method is basically the same. All actual parameters are saved in an array with the same name as the formal parameters. According to actual needs, after reading the elements in this array, you can steam or boil them as you like.

Listing 8: Processing the received actual parameters


private static int sumUp(int... values) {
 int sum = 0;
 for (int i = 0; i < values.length; i++) {
 sum += values[i];
 }
 return sum;
}


5. Forward Variable number of actual parameters

有时候,在接受了一组个数可变的实参之后,还要把它们传递给另一个实参个数可变的方法。因为编码时无法知道接受来的这一组实参的数目,所以“把它们逐一写到该出现的位置上去”的做法并不可行。不过,这并不意味着这是个不可完成的任务,因为还有另外一种办法,可以用来调用实参个数可变的方法。

在J2SE1.5的编译器的眼中,实参个数可变的方法是最后带了一个数组形参的方法的特例。因此,事先把整组要传递的实参放到一个数组里,然后把这个数组作为最后一个实参,传递给一个实参个数可变的方法,不会造成任何错误。借助这一特性,就可以顺利的完成转发了。

清单9:转发收到的实参们


public class PrintfSample {
 public static void main(String[] args) {
  printOut("Pi:%f E:%f\n", Math.PI, Math.E);
 }
 private static void printOut(String format, Object... args) {
  System.out.printf(format, args);
 }
}


6.是数组?不是数组?

尽管在背地里,编译器会把能匹配不确定个实参的形参,转化为数组形参;而且也可以用数组包了实参,再传递给实参个数可变的方法;但是,这并不表示“能匹配不确定个实参的形参”和“数组形参”完全没有差异。

一个明显的差异是,如果按照调用实参个数可变的方法的形式,来调用一个最后一个形参是数组形参的方法,只会导致一个“cannotbeappliedto”的编译错误。

清单10:一个“cannotbeappliedto”的编译错误


private static void testOverloading(int[] i) {
System.out.println("A");
}
public static void main(String[] args) {
testOverloading(1, 2, 3);//编译出错
}


由于这一原因,不能在调用只支持用数组包裹实参的方法的时候(例如在不是专门为J2SE1.5设计第三方类库中遗留的那些),直接采用这种简明的调用方式。

如果不能修改原来的类,为要调用的方法增加参数个数可变的版本,而又想采用这种简明的调用方式,那么可以借助“引入外加函数(IntroduceForeignMethod)”和“引入本地扩展(IntoduceLocalExtension)”的重构手法来近似的达到目的。

7.当个数可变的实参遇到泛型

J2SE1.5中新增了“泛型”的机制,可以在一定条件下把一个类型参数化。例如,可以在编写一个类的时候,把一个方法的形参的类型用一个标识符(如T)来代表,至于这个标识符到底表示什么类型,则在生成这个类的实例的时候再行指定。这一机制可以用来提供更充分的代码重用和更严格的编译时类型检查。

不过泛型机制却不能和个数可变的形参配合使用。如果把一个能和不确定个实参相匹配的形参的类型,用一个标识符来代表,那么编译器会给出一个“genericarraycreation”的错误。

清单11:当Varargs遇上泛型


private static void testVarargs(T... args) {//编译出错
}


造成这个现象的原因在于J2SE1.5中的泛型机制的一个内在约束——不能拿用标识符来代表的类型来创建这一类型的实例。在出现支持没有了这个约束的Java版本之前,对于这个问题,基本没有太好的解决办法。

不过,传统的“用数组包裹”的做法,并不受这个约束的限制。

清单12:可以编译的变通做法


private static void testVarargs(T[] args) {
 for (int i = 0; i < args.length; i++) {
 System.out.println(args[i]);
 }
}


8.重载中的选择问题

Java支持“重载”的机制,允许在同一个类拥有许多只有形参列表不同的方法。然后,由编译器根据调用时的实参来选择到底要执行哪一个方法。

传统上的选择,基本是依照“特殊者优先”的原则来进行。一个方法的特殊程度,取决于为了让它顺利运行而需要满足的条件的数目,需要条件越多的越特殊。

在引入Varargs机制之后,这一原则仍然适用,只是要考虑的问题丰富了一些——传统上,一个重载方法的各个版本之中,只有形参数量与实参数量正好一致的那些有被进一步考虑的资格。但是Varargs机制引入之后,完全可以出现两个版本都能匹配,在其它方面也别无二致,只是一个实参个数固定,而一个实参个数可变的情况。

遇到这种情况时,所用的判定规则是“实参个数固定的版本优先于实参个数可变的版本”。

清单13:实参个数固定的版本优先

如果在编译器看来,同时有多个方法具有相同的优先权,它就会陷入无法就到底调用哪个方法作出一个选择的状态。在这样的时候,它就会产生一个“referenceto被调用的方法名isambiguous”的编译错误,并耐心的等候作了一些修改,足以免除它的迷惑的新源代码的到来。

在引入了Varargs机制之后,这种可能导致迷惑的情况,又增加了一些。例如现在可能会有两个版本都能匹配,在其它方面也如出一辙,而且都是实参个数可变的冲突发生。


public class OverloadingSampleA {
	public static void main(String[] args) {
		testOverloading(1);
		//打印出A
		testOverloading(1, 2);
		//打印出B
		testOverloading(1, 2, 3);
		//打印出C
	}
	private static void testOverloading(int i) {
		System.out.println("A");
	}
	private static void testOverloading(int i, int j) {
		System.out.println("B");
	}
	private static void testOverloading(int i, int... more) {
		System.out.println("C");
	}
}


如果在编译器看来,同时有多个方法具有相同的优先权,它就会陷入无法就到底调用哪个方法作出一个选择的状态。在这样的时候,它就会产生一个“referenceto被调用的方法名isambiguous”的编译错误,并耐心的等候作了一些修改,足以免除它的迷惑的新源代码的到来。

在引入了Varargs机制之后,这种可能导致迷惑的情况,又增加了一些。例如现在可能会有两个版本都能匹配,在其它方面也如出一辙,而且都是实参个数可变的冲突发生。

清单14:左右都不是,为难了编译器


public class OverloadingSampleB {
	public static void main(String[] args) {
		testOverloading(1, 2, 3);
		//编译出错
	}
	private static void testOverloading(Object... args) {
	}
	private static void testOverloading(Object o, Object... args) {
	}
}


另外,因为J2SE1.5中有“Autoboxing/Auto-Unboxing”机制的存在,所以还可能发生两个版本都能匹配,而且都是实参个数可变,其它方面也一模一样,只是一个能接受的实参是基本类型,而另一个能接受的实参是包裹类的冲突发生。

清单15:Autoboxing/Auto-Unboxing带来的新问题


public class OverloadingSampleC {
	public static void main(String[] args) {
		/* 编译出错 */
		testOverloading(1, 2);
		/* 还是编译出错 */
		testOverloading(new Integer(1), new Integer(2));
	}
	private static void testOverloading(int... args) {
	}
	private static void testOverloading(Integer... args) {
	}
}


9.归纳总结

和“用数组包裹”的做法相比,真正的实参个数可变的方法,在调用时传递参数的操作更为简单,含义也更为清楚。不过,这一机制也有它自身的局限,并不是一个完美无缺的解决方案。

以上内容就是关于Java中可变长度参数代码详解的全部内容,希望能帮助到大家。

相关推荐:

PHP 程序员快速进行Java 开发

10 个 有趣的 JavaScript 的脚本语言

如何使用Java定时器Timer

The above is the detailed content of Detailed explanation of variable length parameter code in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn