【问题标题】:What is the difference between "..." and "[]" in Android Java function parameters? [duplicate]Android Java函数参数中的“...”和“[]”有什么区别? [复制]
【发布时间】:2013-11-25 17:10:58
【问题描述】:

我看到了将数组参数放入这样的函数的示例:

function f(String... strings)
{

}

我猜这是说“期望无限数量的字符串”的一种方式。

但它与String[] strings 有何不同?

何时/为什么/如何使用它(三点符号)?

【问题讨论】:

标签: java android parameters optional-parameters optional-arguments


【解决方案1】:

正如您已经猜到的,... 表示法(称为varargs)定义了给定类型的一个或多个参数。在您的方法中,您将在两种情况下都获得 String[] 。区别在于调用方。

public void test1(String... params) {
  // do something with the String[] params
}

public void test2(String[] params) {
  // do something with the String[] params
}

public void caller() {
  test1("abc"); // valid call results in a String[1]
  test1("abc", "def", "ghi"); // valid call results in a String[3]
  test1(new String[] {"abc", "def", ghi"}); // valid call results in a String[3]

  test2("abc"); // invalid call results in compile error
  test2("abc", "def", "ghi"); // invalid call results in compile error
  test2(new String[] {"abc", "def", ghi"}); // valid call
}

【讨论】:

    【解决方案2】:

    它们之间的区别在于调用函数的方式。使用 String var args 可以省略数组创建。

    public static void main(String[] args) {
        callMe1(new String[] {"a", "b", "c"});
        callMe2("a", "b", "c");
        // You can also do this
        // callMe2(new String[] {"a", "b", "c"});
    }
    
    public static void callMe1(String[] args) {
        System.out.println(args.getClass() == String[].class);
        for (String s : args) {
            System.out.println(s);
        }
    }
    public static void callMe2(String... args) {
        System.out.println(args.getClass() == String[].class);
        for (String s : args) {
            System.out.println(s);
        }
    }
    

    Source

    【讨论】:

    • 太棒了。这就是我要找的。最后一件事,我可以用空数组调用callMe1 吗?
    【解决方案3】:

    让我试着一一回答你的问题。

    首先函数 f(String...strings) { } (...) 标识可变数量的参数,这意味着多个参数。 您可以传递 n 个参数。请参考以下示例,

    static int sum(int ... numbers)
    {
       int total = 0;
       for(int i = 0; i < numbers.length; i++)
          total += numbers[i];
       return total;
    }
    

    你可以像这样调用函数 总和(10,20,30,40,50,60);

    其次 String[] 字符串也类似于多个参数,但在 Java 主函数中,您只能使用字符串数组。在这里,您可以在运行时通过命令行传递参数。

    class Sample{
         public static void main(String args[]){
            System.out.println(args.length);
         }
     }
    

    java 样例测试 10 20

    第三,你应该在何时何地使用手段,

    假设你想通过命令行传递参数,运行时也可以使用 String[] 字符串。

    假设您想随时从程序或手动传递 n 个参数,那么您可以使用 (...) 多个参数。

    【讨论】:

      【解决方案4】:

      字符串...字符串正如你所说的不确定数量的字符串 String[] 需要一个数组

      两者的区别在于,数组的大小是固定的。 如果它是函数 f(String[] strings),它只是预期的参数。

      【讨论】:

        猜你喜欢
        • 2020-05-25
        • 2015-08-11
        • 2018-05-14
        • 2015-02-18
        • 2015-08-09
        • 2019-01-17
        • 1970-01-01
        • 2013-01-22
        • 2019-09-04
        相关资源
        最近更新 更多