我看到了将数组参数放入这样的函数的示例:
function f(String... strings)
{
}
我想这是说“期望无限数量的字符串”的一种方式。
但它与 有何不同String[] strings
?
何时/为什么/如何使用它(三点符号)?
我看到了将数组参数放入这样的函数的示例:
function f(String... strings)
{
}
我想这是说“期望无限数量的字符串”的一种方式。
但它与 有何不同String[] strings
?
何时/为什么/如何使用它(三点符号)?
正如您已经猜到的那样,... 表示法(称为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
}
它们之间的区别在于调用函数的方式。使用 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);
}
}
让我试着一一回答你的问题。
首先function 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;
}
你可以调用 sum(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 个参数,那么您可以使用 (...) 多个参数。
字符串...字符串正如您所说的,字符串的数量不定 String[] 需要一个数组
两者的区别在于,数组有一个固定的大小,他被初始化了。如果它是函数 f(String[] strings) 它只是预期的参数。