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

  • 相关阅读:
    修复mac os中的home键和end键
    利用numpy实现list降维
    string与StringBuilder的区别
    mysql 版本,mysqlconnectorjava, application.xml 的 driverclassname 的依赖关系
    linux下创建新用户新数据库并远程访问
    谷歌的JS编码规范链接
    sed命令之多行拷贝
    box2dWeb引擎案例
    SQL Server数据库镜像笔记
    团队项目系统设计
  • 原文地址:https://www.cnblogs.com/ooo0/p/7419777.html
Copyright © 2011-2022 走看看