Definition and use of variable-length parameter methods in Java __java

Source: Internet
Author: User

How to use variable length parameters in Java


Variable-length parameters (varargs) are provided in the JAVA5, which means that the number of indeterminate parameters can be used in the method definition, and a different number of parameters can be invoked for the same method, such as print ("Hello");p rint ("Hello", "Lisi");p rint ("Hello", "John", "Alexia"); The following describes how to define variable-length parameters and how to use variable-length parameters.

1. Definition of variable length parameters

Use... Represents variable-length parameters, such as

Print (String ... args) {

...

}

In a method with variable length parameters, parameters can be used as arrays, for example, all parameter values can be cycled out.

Print (String ... args) {

for (String Temp:args)

SYSTEM.OUT.PRINTLN (temp);

}

2. Calls to methods with variable length parameters

When called, you can give any number of arguments or no parameters, for example:

Print ();

Print ("Hello");

Print ("Hello", "Lisi");

Print ("Hello", "John", "Alexia")

3. Rules for the use of variable-length parameters

3.1 When the method is invoked, if it can match the method of the fixed parameter and can match the method of the variable length parameter, the method of fixing the parameter is selected. Look at the output of the following code:

package com;

A static import is used here for the imported static
java.lang.System.out;

public class Varargstest {public

    void print (String ... args) {for
        (int i = 0; i < args.length; i++) {out
            . println (Args[i]);
        }

    public void print (String test) {
        out.println ("----------");
    }

    public static void Main (string[] args) {
        varargstest test = new Varargstest ();
        Test.print ("Hello");
        Test.print ("Hello", "Alexia");
    }



3.2 If the method to be invoked can match two variable parameters, an error occurs, such as the following code:

package com;

A static import is used here for the imported static
java.lang.System.out;

public class VarArgsTest1 {public

    void print (String ... args) {for
        (int i = 0; i < args.length; i++) {out
            . println (Args[i]);
        }

    public void print (String test,string...args) {
          out.println ("----------");
    }

    public static void Main (string[] args) {
        VarArgsTest1 test = new VarArgsTest1 ();
        Test.print ("Hello");
        Test.print ("Hello", "Alexia");
    }

For the above code, two calls in the Main method cannot be compiled, because the compiler does not know which method call to select, as follows:



3.3 A method can have only one variable long parameter, and this variable length parameter must be the last parameter of the method

The following two method definitions are incorrect.

public void Test (String ... strings,arraylist list) {

}

public void Test (String ... strings,arraylist ... list) {

}

4. Specification for use of variable length parameters

4.1 Avoid method overloads with variable-length parameters: such as 3.1, the compiler knows how to call, but people easily fall into the trap of calling and mistaken

4.2 Do not allow null values and null values to threaten the variable length method, as shown in 3.2, to illustrate the invocation of null values, to give an example again:

Package Com;public class VarArgsTest1 {public

    void print (String test, Integer ... is) {} public

    void print (St Ring Test,string...args) {
          
    } public

    static void Main (string[] args) {
        VarArgsTest1 test = new VarArgsTest1 ();
        test.print ("Hello");
        Test.print ("Hello", null);
    }

You will find that two call compilations do not pass:


Because all two methods match, the compiler doesn't know which one to choose, so there is also a very bad coding habit, that is, the caller hides the argument type, which is very dangerous, not only the caller needs to "guess" which method to invoke, and the caller may also generate internal logic confusion. For this example, you should make the following modifications:

    public static void Main (string[] args) {
        VarArgsTest1 test = new VarArgsTest1 ();
        string[] STRs = null;
        Test.print ("Hello", STRs);
    }

4.3 Write longer methods to follow the rules

Let's take a look at an example and guess if the program can be compiled by:

package com;

public class VarArgsTest2 {

    /**
     * @param args */public
    static void Main (string[] args) {
        //TODO Auto -generated method Stub
        //Up transition
        Base base = new Sub ();
        Base.print ("Hello");
        
        No transition
        Sub Sub = new sub ();
        Sub.print ("Hello");
    }

Base class class
base {
    void print (String ... args) {
        System.out.println ("Base......test");
    }

Subclass, overwrite the parent class method
class Sub extends Base {
    @Override
    void print (string[] args) {
        System.out.println (" Sub......test ");
    }
}

The answer, of course, is that compiling does not pass, is it strange.

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.