[J2SE 1.5] gradually excavated VARARGS

zhaozj2021-02-16  130

Gradually excavation of Varargs simpler delivery of numbers

Sun Haitao (Sun.haitao@126.com)

I was originally published on August 5, 2004, and finally revised on August 19, 2004.

J2SE 1.5 provides the "VARARGS" mechanism. With this mechanism, it can be defined and a plurality of ginseng matching multiple actors. Thereby, it can be used to deliver a variable argument in a simpler way. This article describes the use of this mechanism, and several problems when this mechanism is interacting between arrays, generic, and overloaded.

Up to J2SE 1.4, it has not been able to define a variable number of variables in the Java program - because Java requires the quantity and type of arguments and parameters, and the number of ginseng It is already fixed when defining the method. Although it can provide a version with different numbers of ginseng by overloading mechanism, this still does not achieve any changes to arbitrary changes in the quantity of the argument.

However, some methods are semantically requiring that they must accept a variable-variable argument - such as a famous main method, it is necessary to accept all command line parameters as arguments, and the number of command line parameters is not determined. Down.

For this issue, it is conventionally generally to adopt the practice of "using an array to package the unintended" to be delivered ".

1. Use array parcels

The approach of "Unrecognizable Parcels" can be divided into three steps: First, a array of parameters are defined for this method; then when calling, generate an array containing all the arguments to be passed; finally, put this array as A stream pass passed.

This approach can effectively reach the purpose of "let the method can accept a variable parameter", but the form is not simple enough when calling.

The VARARGS mechanism is provided in J2SE 1.5, which allows direct definitions to match the ginseng matching multiple actors. Thereby, it can be used to deliver a variable argument in a simpler way.

VARARGS meaning

Generally, "VARARGS" is the meaning of "variable number of arguments". Sometimes it is also known as "variable arguments", but because this is called the method, there is no explanation, so the meaning is slightly blurred.

2. Define a variable number of real references

As long as the "type" and "parameter name" in a "parameter name" are omitted, it can make it and uncertain. Guan match. And a method with such a ginseng is a way to be a variable number.

Listing 1: A variable method for first parameters

Private static int sumup

INT ... VALUES) {

}

Note that only the last meticulum can be defined as "can and uncertainty match match". Therefore, there can only be one such ginseng in one method. In addition, if this method has other ginseng, put them in the front position.

The compiler will convert this last-form be ginseng in the back, and make a marker in the compiled class file indicating that this is a variable number of reference.

Listing 2: Secret form of a variable method of realism

Private static int sumup

Int [] value) {

}

Since there is such transformation, it is no longer possible to define a method of signing and the transformation method.

Listing 3: Combination of compilation errors

Private static int sumup

INT ... VALUES) {

}

Private static int sumup

Int [] value) {

}

Blank survival problem

According to J2SE 1.5 grammar, the blank character in front of "..." is available. This will add a blank character in front of "...", such as "Object ... Args") and in front of "...", there is no blank character (shaped like "Object ... Args") Writing. Because the Java Code Conventions currently cooperated with J2SE 1.5 yet is not officially released, it is unable to know which method is orthodontics. However, considering the array parameters, there are "Object [] args" and "Object [] args" two kinds of writing methods, and the orthodox way is not "[]" to add a blank character before "[]", which seems to take the "Object .. ARGS "is more coordinated in whole. 3. Calling the number of variable numbers

As long as the acts to be passed to the corresponding position, a variable method can be called. No other steps are required.

Listing 4: You can pass a number of arguments

Sumup

1, 3, 5, 7);

In the back, the compiler will transform this call process to the form of "array parcels":

Listing 5: Stolen array creation

Sumup

NEW INT [1, 2, 3, 4});

In addition, "uncertainty" said here also includes zero, so this call is also reasonable:

Listing 6: You can also pass zero-arguments

Sumup

();

This call approach is equivalent to the effect after the compiler is secretly transformed:

Listing 7: Zero-acts corresponding empty array

Sumup (new int []

{});

Note that the passed is an empty number, not NULL. This can be handled in a unified form, without having to detect which case belongs to.

4. Handle the number of variable

Treat a variable-variety of arguments, and the way to handle array is basically the same. All of the arguments are saved to an array of one and the meta-ginseng. According to the actual needs, after reading the elements in this array, you can steam, you can freely.

Listing 8: Processing received

Private Static int SUMUP (Int ...

VALUES {

INT SUM = 0;

For (int i = 0; i <

VALUES.LENGTH; I ) {

SUM =

VALUES [I];

}

Return SUM;

}

5. Forwarding the number of variable

Sometimes, after accepting a group of variable-to-arguments, it is also possible to pass them to another number of variable numbers. Because you can't know the number of unscrupulous parameters when encoding, the practice of "writing them to the position of the appearance" is not feasible. However, this does not mean that this is an unpleasant task, because there is another way to call the number of variable numbers in real parameters.

In the eye of the compiler of J2SE 1.5, the number of variable-numbered methods is the first special case of the method of array. Therefore, in advance, put the entire group to be delivered into an array, then use this array as the last argument, pass to a variable-numbered method, and will not cause any errors. With this feature, it can be successfully completed smoothly.

Listing 9: Forwarding received

Public class printfsample {

Public static void main (String [] args) {

// Print "PI: 3.141593 E: 2.718282"

Printout ("pi:% f e:% f / n", Math.Pi, Math.e;

}

Private static void printout (String Format,

Object ... args) {

// j2se 1.5 in PRINTSTREAM new printf (String Format, Object ... ARGS) method system.out.printf (Format,

ARGS);

}

}

"Printf" and "Sprintf" in Java

The printf in the C language (output string according to a certain format) and Sprintf (in a certain format combined string) are examples using the VARARGS mechanism. In J2SE 1.5, similar features are provided in the Java.io.PrintStream class and Java.lang.String classes, respectively.

The function of outputting strings at a certain format can be implemented by calling the printf (String Format, Object ... ARGS) method of the PrintStream object.

Press a certain format to combine the operation of the string, you can do it by calling the String Format (String Format, Object ... ARGS) static method of the String class.

6. Is it an array? Not an array?

Although in the back, the compiler will match the parametric parametric parameters that can be matched, converted into array parameters; and can also be used in array packages, and then pass it to the real parameter variable method; however, This does not mean that there is no difference in "Meeting to match uncertainty" and "array ginseng".

A significant difference is that if a method of calling a last type is a number of group-type parameters, it will only cause a "Cannot Be Applied to" compilation error.

Listing 10: Compile error in "cannot beapplied to"

Private static void testoverloading

int [] i) {

System.out.println ("a");

}

Public static void main (String [] args) {

TestoverLoading

1, 2, 3); // Compiling an error

}

For this reason, this concise call approach is directly adopted when calling only the method of parcening with arranging arguments (for example, it is not specifically for J2SE 1.5).

If the original class cannot be modified, add the number of variable variables to the method to be called, and want to use this concise call mode, then "Introducted Foreign Method" and "introducing local extensions The reconstruction of the INTOduce local extension "is approximated.

7. When a number variable colony encounters a generic

The "generic" mechanism is added in J2SE 1.5, which can be parametric under certain conditions. For example, when writing a class, the type of a method is represented by an identifier (e.g., t), as for this identifier, what type is indicated, then specifies when the instance of this class is generated. . This mechanism can be used to provide a more fully code reuse and more stringent compile time type checks.

However, the generic mechanism cannot be used in combination with a variable shape. If you represent the type of the ginseng that can match and does not confirm the ginseng, use an identifier to represent a "generic array code" error.

Listing 11: When VARARGS encounters a generic

Private stat

void testvarargs

T ... args) {// Compile error

}

This phenomenon is caused by an intrinsic constraint of generic mechanism in J2SE 1.5 - the type of identifier can be used to create this type of instance. Before the Java version without this constraint, there is basically no good solution for this issue. However, the practice of traditional "array wrapping" is not limited by this constraint.

Listing 12: Workability can be compiled

Private stat

void testvarargs

T [] args) {

For (int i = 0; i

System.out.println (Args [i]);

}

}

8. Choice problems in overload

Java supports the mechanism of "overload", allowing many ways to have different forms in the same class. Then, the compiler is selected to perform which method to perform based on the arguments when the call is called.

Traditional choices are basically carried out in accordance with the principles of "special person priority". A special extent of a method depends on the number of conditions that need to be satisfied in order to make it smoothly run.

After introducing the Varargs mechanism, this principle is still applicable, just to consider the problem - traditionally, in all versions of the overload method, only the number of the quantity is further consistent with the quantity of the argument. Consider the qualifications. But after the VARARGS mechanism is introduced, you can match the two versions, don't be born in other aspects, just a real parameter fixed, and a real number of becomes variable.

When this is encountered, the judgment rule used is "The real version of the number of fixed numbers is preferred for the real number of variables."

Listing 13: Real parameter fixed version priority

Public class overloadingsamplea {

Public static void main (String [] args) {

TestoverLoading

1); // Print A

TestoverLoading

1, 2); // Print B

TestoverLoading

1, 2, 3); // Print 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, there are multiple methods with the same priority, which will fall into which method cannot be called which method makes a selected state. In this case, it produces a compilation error of "Reference TO-called Method IS Ambiguous", and patient waiting for some modifications, enough to avoid the arrival of its confused new source code.

After introducing the VARARGS mechanism, this may result in confusion and add some. For example, there may be two versions that can be matched, and other aspects are also exiled, and they are all variable conflicts that are measured.

Listing 14: The left and right are not, for the compiler

Public class overloadingsampleb {

Public static void main (String [] args) {

TestoverLoading (1, 2, 3); // Compile error

}

Private static void testoverloading

Object ... args) {

}

Private Static Void TestoverLoading (Object O, Object ... ARGS) {

}

}

In addition, because there is a "autoboxing / auto-unboxing" mechanism in J2SE 1.5, it is possible to match two versions, and it is the same as the number of becomings, and the other aspect is exactly the same. It is just a acceptable implementation. At the essential type, and the other can accept the argument of the parcels.

Listing 15: A new issue brought by autoboxing / auto-unboxing

Public class overloadingsamplec {

Public static void main (String [] args) {

/ * Compile error * /

TestoverLoading

1, 2);

/ * Or compilation error * /

TestoverLoading

NEW INTEGER (1), New Integer (2));

}

Private static void testoverloading

INT ... ARGS) {

}

Private static void testoverloading

Integer ... args) {

}

}

9. Summary

Compared to the "use of array package", the real real parameter variable method is more simple, and the meaning is more clear when the call is called. However, this mechanism also has its own limitations, not a perfect solution.

Reference resource

You can find the link to download J2SE 1.5 SDK and its documentation through Sun's Java Technology page. The latest version is J2SDK 5.0 Beta 2. "JSR 201: Extending The Java Programming Language with Enumeration, Autoboxing, Enhanced for loops and static import" new language features in J2SE 1.5 are defined. Although there is no clear mention in the title, the VARARGS mechanism is also there. Calvin Austin In "J2SE 1.5 in a nutshell", the comparative introduction is a more comprehensive introduction to the new features of J2SE 1.5. John Zukowski introduced how to start using J2SDK 1.5 basics in "Tam Tiger: Tiger Preview". However, this article is written in accordance with the status of J2SDK 1.5 Alpha version, so some details (such as download address and default installation path) have changed. John Zukowski introduces a measures for string formatting using J2SE 1.5 in the article "Tame Tiger: Format Output". Gilad Bracha In "Generics In The Java Programming Language", meticulous introduces the use of generic mechanisms in J2SE 1.5 and various restrictions. Martin Fowler Reconstructs "Refactoring - Improving The Design Of EXISTING CODE" - Improved Code of Design of Code " In MoVing Features Between Objects, a reconstruction technique called "Introducture Foreign Method" and "Introduction Local Extension" is introduced. Gilad Bracha, James Gosling, Bill Joy and Guy Steele In the "Overloading" section in the "Classes" in the "The Java Language Specification, 2nd Edition" chapter "Method Invocation Expressions" in the "Expression" chapter An in-depth discussion of overloading is discussed. However, this book is written in accordance with the status of J2SDK 1.2, so there is no completely cover the actual situation in J2SE 1.5. revise history

August 19, 2004

A brief introduction to several new ways to make string formatted by the VARARGS mechanism.

A link to the content of the formatted output in J2SE 1.5 is given.

August 5, 2004

Originally published.

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

New Post(0)