Android Java函数参数中"..."和"[]"之间有什么区别?

mob*_*ici 1 java parameters android optional-parameters optional-arguments

我看到一个例子,其中一个数组参数放到这样的函数:

function f(String... strings)
{

}
Run Code Online (Sandbox Code Playgroud)

我猜这是说"期望无限数量的字符串"的一种方式.

但它有什么不同String[] strings?

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

tma*_*dry 5

正如您已经猜到的那样,......符号(称为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
}
Run Code Online (Sandbox Code Playgroud)