In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will share with you about the common uses of variable parameters in Java. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Wrap the argument in an array
The practice of "wrapping arguments in an array" can be divided into three steps: first, define an array of parameters for the method; then, when called, generate an array containing all the arguments to be passed; finally, pass the array as an argument.
This approach can effectively achieve the goal of "allowing the method to accept a variable number of parameters", but the form of the call is not simple enough.
The Varargs mechanism is provided in J2SE 1.5, which allows you to directly define parameters that can match multiple arguments. Thus, a variable number of arguments can be passed in a simpler way.
The meaning of Varargs
Generally speaking, "Varargs" means "variable number of arguments". It is sometimes referred to simply as "variable arguments", but because this term does not specify what is variable, the meaning is a little vague.
two。 A method for defining a variable number of arguments
As long as you add three consecutive "between the" type "and" parameter name "of a parameter, you can match it with an uncertain argument. A method with such parameters is a method with a variable number of arguments.
Listing 1: a method with variable arguments
Private static int sumUp (int... Values) {}
Note that only the last parameter can be defined as "matching an uncertain argument". Therefore, there can be only one such parameter in a method. In addition, if there are other parameters in this method, put them in the front position.
The compiler will secretly convert this last parameter into an array parameter and mark it in the compiled class file to indicate that this is a method with a variable number of arguments.
Listing 2: secret form of a method with variable number of arguments
Private static int sumUp (int [] values) {}
Because of such a transformation, you can no longer define a method for this class that is consistent with the transformed method signature.
Listing 3: combinations that cause compilation errors
Private static int sumUp (int... Values) {} private static int sumUp (int [] values) {}
3. Call a method with a variable number of arguments
As long as you write the arguments to be passed one by one to the appropriate location, you can call a method with a variable number of arguments. No other steps are needed.
Listing 4: several arguments can be passed
SumUp (1,3,5,7)
Secretly, the compiler converts this calling procedure into the form of "wrapping arguments in an array":
Listing 5: secretly appearing array creation
SumUp (new int [] {1,2,3,4})
In addition, the "uncertainty" here also includes zero, so such a call makes sense:
Listing 6: zero arguments can also be passed
SumUp ()
The effect of this calling method after being secretly converted by the compiler is equivalent to this:
Listing 7: zero argument corresponding empty array
SumUp (new int [] {})
Notice that an empty array is passed, not null. In this way, it can be dealt with in a unified form without having to detect which situation it belongs to.
4. Deal with a variable number of arguments
The method of dealing with a variable number of arguments is basically the same as dealing with array arguments. All arguments are stored in an array with the same name as the parameter. According to the actual needs, after reading out the elements in this array, you can steam and boil at will.
Listing 8: processing received arguments
Private static int sumUp (int... Values) {int sum = 0; for (int I = 0; I < values.length; iTunes +) {sum + = values [I];} return sum;}
5. Forward a variable number of arguments
Sometimes, after receiving a set of variable arguments, you have to pass them to another method with a variable number of arguments. Because it is impossible to know the number of arguments accepted when coding, it is not feasible to "write them down one by one to where they should appear". However, this does not mean that this is an impossible task, because there is another way to call a method with a variable number of arguments.
In the eyes of the compiler of J2SE 1.5, a method with a variable number of arguments is a special case of a method that ends up with an array of arguments. Therefore, it does not cause any error to put the entire set of arguments to be passed into an array, and then pass this array as the last argument to a method with a variable number of arguments. With the help of this feature, the forwarding can be completed smoothly.
Listing 9: forward received arguments
Public class PrintfSample {public static void main (String [] args) {printOut ("Pi:%f Eviso% f\ n", Math.PI, Math.E);} private static void printOut (String format, Object...) Args) {System.out.printf (format, args);}}
6. Is it an array? Not an array?
Although secretly, the compiler converts parameters that can match uncertain arguments into array parameters, and it can also wrap arguments in an array and pass them to methods with a variable number of arguments, this does not mean that there is no difference between "parameters that can match uncertain arguments" and "array parameters".
One obvious difference is that calling a method whose last parameter is an array parameter in the form of a method with a variable number of arguments will only result in a "cannot be applied to" compilation error.
Listing 10: a compilation error for "cannot be applied to"
Private static void testOverloading (int [] I) {System.out.println ("A");} public static void main (String [] args) {testOverloading (1,2,3); / / compilation error}
For this reason, this concise invocation cannot be used directly when calling methods that only support wrapping arguments in arrays (such as those left over from third-party class libraries that are not specifically designed for J2SE 1.5).
If you cannot modify the original class and add a version with a variable number of parameters to the method to be called, and you want to use this concise way of calling, you can approximately achieve the goal by means of the refactoring techniques of "introducing additional functions (Introduce Foreign Method)" and "introducing local extensions (Intoduce Local Extension)".
7. When a variable number of arguments encounters generics
A new "generic" mechanism has been added in J2SE 1.5, which can parameterize a type under certain conditions. For example, when writing a class, the type of the formal parameter of a method can be represented by an identifier (such as T). As to what type this identifier represents, it can be specified when an instance of the class is generated. This mechanism can be used to provide fuller code reuse and stricter compile-time type checking.
However, the generic mechanism cannot be used with a variable number of parameters. If the type of a parameter that matches an uncertain argument is represented by an identifier, the compiler will give a "generic array creation" error.
Listing 11: when Varargs encounters generics
Private static void testVarargs (T... Args) {/ / compilation error}
The reason for this is an inherent constraint of the generics mechanism in J2SE 1.5-you cannot create an instance of this type with a type represented by an identifier. Before the emergence of Java versions that supported without this constraint, there was almost no good solution to this problem.
However, the traditional practice of "wrapping in arrays" is not subject to this constraint.
Listing 12: workarounds that can be compiled
Private static void testVarargs (T [] args) {for (int I = 0; I < args.length; iTunes +) {System.out.println (args [I]);}}
8. Selection problem in overloading
Java supports the "overloading" mechanism, which allows you to have many different methods in the same class with only formal parameter lists. It is then up to the compiler to choose which method to execute based on the arguments at the time of the call.
Traditionally, choices are basically made in accordance with the principle of "giving priority to the special". The special degree of a method depends on the number of conditions that need to be met in order for it to run smoothly. The more conditions are needed, the more special they are.
This principle still applies after the introduction of the Varargs mechanism, except that the issues to be considered have been enriched-traditionally, among the versions of an overloaded method, only those with exactly the same number of formal parameters and arguments are eligible for further consideration. However, after the introduction of the Varargs mechanism, there can be a match between the two versions, and there is no difference in other aspects, except that the number of arguments is fixed and the number of arguments is variable.
In this case, the decision rule used is that "the version with a fixed number of arguments takes precedence over the version with a variable number of arguments."
Listing 13: version with a fixed number of arguments takes precedence
If, in the compiler's view, multiple methods have the same priority at the same time, it will fall into a state where it is unable to make a choice about which method to call. At such times, it generates a compilation error of "reference to called method name is ambiguous" and patiently waits for the arrival of new source code that has been modified enough to avoid its confusion.
With the introduction of the Varargs mechanism, this situation that can lead to confusion has increased a little more. For example, there may now be two versions that match, which are the same in other respects, and both are conflicts with a variable number of arguments.
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, multiple methods have the same priority at the same time, it will fall into a state where it is unable to make a choice about which method to call. At such times, it generates a compilation error of "reference to called method name is ambiguous" and patiently waits for the arrival of new source code that has been modified enough to avoid its confusion.
With the introduction of the Varargs mechanism, this situation that can lead to confusion has increased a little more. For example, there may now be two versions that match, which are the same in other respects, and both are conflicts with a variable number of arguments.
Listing 14: neither left nor right, making it difficult for the compiler
Public class OverloadingSampleB {public static void main (String [] args) {testOverloading (1,2,3); / / compilation error} private static void testOverloading (Object... Args) {} private static void testOverloading (Object o, Object... Args) {}}
In addition, because of the "Autoboxing/Auto-Unboxing" mechanism in J2SE 1.5, it is possible that both versions can match, and the number of arguments is variable, and other aspects are exactly the same, except that one acceptable argument is the basic type, and the other acceptable argument is the collision of the wrapper class.
List the new problems brought about by 15:Autoboxing/Auto-Unboxing
Public class OverloadingSampleC {public static void main (String [] args) {/ * compilation error * / testOverloading (1,2); / * compilation error * / testOverloading (new Integer (1), new Integer (2));} private static void testOverloading (int...) Args) {} private static void testOverloading (Integer... Args) {}}
Thank you for reading! This is the end of the article on "what are the common uses of variable parameters in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.