zoukankan      html  css  js  c++  java
  • java 不定长参数

    一,不定长参数的规定

      一个方法只能有一个不定长参数,并且这个不定长参数必须是该方法的最后一个参数.

    示例:

    public class VariArgs {
    
        public static void main(String[] args) {
            test();
            test("aaa");
            test("aaa", "bbb");
            test("aaa", "bbb", "ccc");
        }
    
        public static void test(String... args) {
            System.out.println(args.getClass());
            for (String arg : args) {
                System.out.println(arg);
            }
        }
    }

    二,注意事项

    1.在调用方法的时候,如果能够和固定参数的方法匹配,也能够与可变长参数的方法匹配,则选择固定参数的方法

    public class VarArgsTest {
    
        public void print(String... args) {
            for (int i = 0; i < args.length; i++) {
                System.out.println(args[i]);
            }
        }
    
        public void print(String test) {
            System.out.println("----------");
        }
    
        public static void main(String[] args) {
            VarArgsTest test = new VarArgsTest();
            test.print("hello");
            test.print("hello", "alexia");
        }
    }

    结果:

    2.如果要调用的方法可以和两个可变参数匹配,则出现错误

    public class VarArgsTest1 {
    
        public void print(String... args) {
            for (int i = 0; i < args.length; i++) {
                System.out.println(args[i]);
            }
        }
    
        public void print(String test, String... args) {
            System.out.println("----------");
        }
    
        public static void main(String[] args) {
            VarArgsTest1 test = new VarArgsTest1();
            test.print("hello");
            test.print("hello", "alexia");
        }
    }

    错误:

    http://blog.csdn.net/djun100/article/details/10134419

    http://www.cnblogs.com/lanxuezaipiao/p/3190673.html

  • 相关阅读:
    E
    C. Connect Three(构造)
    判断矩形相交的方法
    字典树&&01字典树专题&&对字典树的理解
    J
    kmp专题
    Python 字典 popitem() 方法
    Python 字典 pop() 方法
    Python 字典(Dictionary) values()方法
    Python 字典(Dictionary) update()方法
  • 原文地址:https://www.cnblogs.com/ooo0/p/7419777.html
Copyright © 2011-2022 走看看