Create a way to accept variable parameters

xiaoxiao2021-03-06  73

From Java 1.5, we can create methods for accepting variable parameters. Like many other enhancements in Java 1.5, this enhancement is purely a change in grammar. The syntax for creating a way to accept variable parameters is as follows:

Public void foo (String ... names) {}

Calling the method of receiving variable number parameters is similar to that of the call to accept a fixed number parameter:

Foo ("Joe", "Mandy");

or

Foo ("Joe");

or

FOO ("Joe", "Mandy", "David");

Behind the scene we see, the compiler creates an array (that is, a string array), load your variable into it, and incorporate the array as a parameter.

In order to let you believe that the following code snippets call a method with only one String array parameter. Compiling and execution of all code is the same as we expect.

Foo (new string [] {"joe", "mandy", "david"));

The variable parameter method can also be used for the original data type, the following code snippet can explain:

Public void bar (int ... Vals) {} ... bar (3, 9, 100);

The following code contains two methods that accept variable number parameters. Run the following code to see if the result is the same as you expect.

Public class varigstip {public static void main (string [] args) {foo ("one", "two", "three"); foo (new string [] {"one", "two", "three"}) Bar (1, 2, 45, 101);} static void foo (string ... name) {system.out.println (s);}} static void bar (int .. {for (int Num: VALS) {system.out.println (num);}}}

Note: The code in this prompt is compiled using Java Build 1.5.0-Beta-B32c under Windows 2000. To compile the code in this prompt, you must use the Javac "-Source 1.5" option.

转载请注明原文地址:https://www.9cbs.com/read-120780.html

New Post(0)