Home > Java > javaTutorial > body text

Examples of using variable length parameters in Java

零下一度
Release: 2018-05-29 09:20:53
Original
1581 people have browsed it

Variable-length parameters (varargs) are provided in Java5, that is, an uncertain number of parameters can be used in the method definition, and the same method can be called with a different number of parameters, such as print("hello"); print("hello","lisi");print("hello","Zhang San", "alexia");The following describes how to define variable length parameters and how to use variable length parameters.

1. Definition of variable-length parameters

Use... to indicate variable-length parameters, such as

print(String... args){
   ...
}
Copy after login

in methods with variable-length parameters Parameters can be used as arrays, for example, all parameter values ​​can be output in a loop.

print(String... args){
   for(String temp:args)
      System.out.println(temp);
}
Copy after login

2. Calling methods with variable length parameters

You can give any number of parameters or no parameters when calling, for example:

print();
print("hello");
print("hello","lisi");
print("hello","张三", "alexia")
Copy after login

3. Rules for using variable-length parameters

3.1 When calling a method, if it can match a method with fixed parameters or a method with variable-length parameters, choose the method with fixed parameters. method. Look at the output of the following code:

package com;

// 这里使用了静态导入
import 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");
    }
}
Copy after login

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

package com;

// 这里使用了静态导入
import 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");
    }
}
Copy after login

For the above code, main Both calls in the method cannot be compiled because the compiler does not know which method to call, as shown below:

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

The following two method definitions are wrong.

public void test(String... strings,ArrayList list){

}

public void test(String... strings,ArrayList... list){

}

4. Specifications for the use of variable-length parameters

4.1 Avoid overloading methods with variable-length parameters: as in 3.1 , although the compiler knows how to call, people can easily fall into calling traps and misunderstandings

4.2 Don’t let null values ​​and empty values ​​threaten variable length methods, as shown in 3.2, in order to illustrate the calling of null values, Give another example:

package com;public class VarArgsTest1 {

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

    public void print(String test,String...args ){
          
    }

    public static void main(String[] args) {
        VarArgsTest1 test = new VarArgsTest1();
        test.print("hello");
        test.print("hello", null);
    }
}
Copy after login

At this time, you will find that both calls fail to compile:

Because both methods match, the compiler does not know which one to choose, so it reports an error, here At the same time, there is also a very bad coding habit, that is, the caller hides the actual parameter type, which is very dangerous. Not only does the caller need to "guess" which method to call, but the callee may also have internal logic confusion. Condition. For this example, the following modifications should be made:

    public static void main(String[] args) {
        VarArgsTest1 test = new VarArgsTest1();
        String[] strs = null;
        test.print("hello", strs);
    }
Copy after login

4.3 Overwriting variable length methods must also follow the rules

Let’s look at an example. Guess whether the program can be compiled and passed:

package com;

public class VarArgsTest2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 向上转型
        Base base = new Sub();
        base.print("hello");
        
        // 不转型
        Sub sub = new Sub();
        sub.print("hello");
    }

}

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

// 子类,覆写父类方法
class Sub extends Base {
    @Override
    void print(String[] args) {
        System.out.println("Sub......test");
    }
}
Copy after login

The answer is of course that it cannot be compiled. Doesn’t it feel strange?

The first one can be compiled and passed. Why is this? In fact, the base object upwardly transforms the subclass object sub. The formal parameter list is determined by the parent class, and of course it can pass. Looking at the direct call from the subclass, the compiler sees that the subclass has overridden the print method of the parent class, so it must use the print method redefined by the subclass. Even if the parameter list does not match, it will not run to the parent class. Try matching again, because once you find it, you won’t look for it anymore, so there is a type mismatch error.

This is a special case. The overridden method parameter list can be different from the parent class. This violates the definition of overriding and will cause inexplicable errors.

Here, summarize the conditions that must be met for overwriting:

(1) The overriding method cannot reduce access rights;

(2) The parameter list must be the same as the one being rewritten The method is the same (including the display form);

(3) The return type must be the same as the overridden method or its subclass;

(4) The overridden method cannot throw a new Exceptions, or exceptions that exceed the scope of the parent class, but can throw fewer, more limited exceptions, or no exceptions.

Finally, give an example with traps. Everyone should know the output:

package com;

public class VarArgsTest {
    public static void m1(String s, String... ss) {
        for (int i = 0; i < ss.length; i++) {
            System.out.println(ss[i]);
        }
    }

    public static void main(String[] args) {

        m1("");
        m1("aaa");
        m1("aaa", "bbb");
    }
}
Copy after login

The above is the detailed content of Examples of using variable length parameters in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template