A detailed explanation of Varargs mechanism in Java

Source: Internet
Author: User

The new version of J2SE 1.5 provides a mechanism for "Varargs". Use this mechanism to define parameters that can match multiple arguments. This makes it possible to pass a variable number of arguments in a simpler way. This article describes how this mechanism is used, and how it interacts with arrays, generics, and overloads.

(xi ' An core science garden http://www.029xhl.com/)

Before J2SE 1.4, Java programs had been unable to define a variable number of arguments-because Java requires both the number and type of arguments (Arguments) and formal parameters (Parameters) to match each other, and the number of formal parameters is fixed when the method is defined. Although it is possible to provide a version with a different number of parameters for the same method by overloading the mechanism, this still does not achieve the purpose of arbitrarily changing the number of arguments.

However, the semantics of some methods require that they be able to accept a variable number of arguments-such as the well-known main method, which requires that all command-line arguments be accepted as arguments, and that the number of command-line arguments cannot be determined at all beforehand.

Traditionally, the use of an array to wrap the arguments to be passed is generally used to cope with this problem.

Wrap an argument with an array

The "Wrap arguments with arrays" approach can be divided into three steps:

First, define an array-type parameter for this method;

Second, at the time of invocation, generate an array containing all the arguments to be passed;

Third, pass the array as an argument in the past.

This practice is called when the form is not simple enough. The varargs mechanism is provided in J2SE 1.5, allowing direct definition of formal parameters that can match multiple arguments. Thus, it is possible to pass a variable number of arguments in a simpler way.

  The meaning of varargs

Generally speaking, "Varargs" is the meaning of "variable number of arguments". It is sometimes referred to simply as "variable arguments", but because it does not indicate what is mutable, the meaning is somewhat blurred.

  Methods for defining the variable number of arguments

Simply add three consecutive "." Between "type" and "parameter name" of a formal parameter. (That is, "...", an ellipsis in an English sentence), it can be matched to an indeterminate argument. A method with such a parameter is a variable number of arguments.

Example: A method with variable number of arguments

private static int SumUp (int ... values) {

}

Note that only the last formal parameter can be defined as "can and does not have an argument to match". Therefore, there can be only one such parameter in a method. Also, if the method has other parameters, put them in the front position.

The compiler converts the last parameter into an array parameter behind the box and makes a tick in the compiled class file, indicating that this is a variable number of arguments.

Example: Secret form of a method with variable number of arguments

private static int SumUp (int[] values) {

}

Because of this transformation, it is no longer possible to define a method that is consistent with the converted method signature for this class.

Example: A combination that causes compilation errors

private static int SumUp (int ... values) {

}

private static int SumUp (int[] values) {

}

  A blank question

According to the syntax of J2SE 1.5, whitespace characters in front of "..." are optional. This will be preceded by "..." by adding white space characters (shaped like "object ... args") and not preceded by "..." with whitespace characters (shaped like "object ... args") in two ways. Because the Java Code Conventions, currently in conjunction with J2SE 1.5, is not officially released, it is not possible to know which one is more orthodox. However, considering that the array parameters also have "Object [] args" and "object[" args "two ways of writing, and the orthodox notation is not" [] "before the addition of white space characters, it seems to take a blank" object ... args "In the overall way more coordinated.

  Methods to invoke a variable number of arguments

You can call a method with a variable number of arguments, as long as you write the arguments you want to pass to a corresponding location. No additional steps are required.

Example: You can pass a number of arguments

SumUp (1, 3, 5, 7);

This method of invocation is the result of the compiler's secret conversion, which is equivalent to this:

Example: 0 argument corresponds to an empty array

SumUp (New int[]{});

Note that passing in the past is an empty array, not NULL. This can be done in a uniform form, without having to detect exactly which case it belongs to.

   Handle a variable number of arguments

The method of dealing with a variable number of arguments is basically the same as the method for working with array arguments. All arguments are saved to an array with the same name as the parameter. According to the actual needs, the elements in this array after reading, you can be arbitrary.

Example: processing the Received arguments

private static int SumUp (int ... values) {

int sum = 0;

for (int i = 0; i < values.length; i++) {

Sum + = Values[i];

}

return sum;

}

 Forward a variable number of arguments

Sometimes, after you accept a set of variable arguments, you pass them to another method with a variable number of arguments. Because there is no way to know the number of accepted sets of arguments in the code, it is not feasible to "write them down to where they appear". However, this does not mean that this is an unfinished task because there is another way to invoke a variable number of arguments.

In the eyes of the compiler for J2SE 1.5, the variable number of arguments is a special case of the method with the last array parameter. Therefore, the entire set of arguments to be passed is placed in an array beforehand, and the array is passed as the last argument to a variable number of arguments, without causing any errors. With this feature, the forwarding can be completed smoothly.

  When a variable number of arguments encounters a generic

A "generic" mechanism has been added to J2SE 1.5 to parameterize a type under certain conditions. For example, when writing a class, the type of the formal parameter of a method is represented by an identifier (such as T), and when the identifier exactly represents what type it is, it is specified when the instance of the class is generated. This mechanism can be used to provide more full code reuse and stricter compile-time type checking.

However, a generic mechanism cannot be used with a variable number of parameters. If the type of a formal parameter that matches an indeterminate argument is represented by an identifier, the compiler will give a "Generic array creation" error.

   Selection problems in overloading

Java supports the "overloaded" mechanism, which allows for a number of different methods that have only formal parameter lists in the same class. The compiler then chooses which method to execute based on the arguments that are called.

The traditional choice is basically based on the principle of "special preference". The special degree of a method depends on the number of conditions that need to be met in order for it to run smoothly, and the more specific the requirement is.

After the introduction of the varargs mechanism, this principle still applies, but the issues to be considered are enriched-traditionally, in the various versions of an overloaded method, only those with the same number of formal parameters as the number of actual parameters have been further considered. However, after the introduction of the varargs mechanism, it is possible to have two versions that can match, in other respects also indistinguishable, only a fixed number of arguments, and a variable number of arguments.

When this happens, the decision rule is "a version with a fixed number of arguments takes precedence over a variable number of arguments."

Example: A fixed version of the argument number takes precedence

public class Overloadingsamplea {

public static void Main (string[] args) {

Testoverloading (1);//Print out a

Testoverloading (1, 2);//Print out B

Testoverloading (1, 2, 3);//Print out 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");

}

}

If, in the compiler's view, more than one method has the same priority, it will fall into a state where it is impossible to make a selection of which method to invoke. At this time, it will produce a "reference to be called method name is ambiguous" compile error, and patiently wait for some changes, enough to exempt it from the confusion of the arrival of the source code.

After the introduction of the varargs mechanism, this could lead to confusion and a number of additional cases. For example, there may be two versions that can match, and in other respects, they are conflicting occurrences with variable number of arguments.

A detailed explanation of Varargs mechanism in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.