从Java 5开始,Java语言对方法参数支持一种新写法,叫 可变长度参数列表,其语法就是类型后跟...,表示此处接受的参数为0到多个Object类型的对象,或者是一个Object[]。

public static void main(String[] args) throws IOException {
    test("ni", "hao", "ma", "?");
    System.out.println();
    String[] list = {"wo","hen","hao",",","xie","xie","!"};
    test(list);
}

public static void test(String... arg){
    for (String anArg : arg) {
        System.out.print(anArg + ' ');
    }
}

  最后输出:

    ni hao ma ?
    wo hen hao , xie xie !

 

  定义三个点,相当于是定义了一个对象数组,它的长度同数组获取长度一样,使用 .length ,只是它可以直接把数组里的元素写到参数里
  需要注意的是,不能在这个参数后面再定义别的参数,编译会出错

 

相关文章:

  • 2022-01-23
  • 2021-08-13
  • 2021-10-24
  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2021-08-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2022-12-23
  • 2022-02-08
相关资源
相似解决方案