在 Java 中定义一个字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18214985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:22:59  来源:igfitidea点击:

Define a String array in Java

javaarraysstringmain

提问by Ruchira Gayan Ranaweera

In java we can define main()method as both these ways.

在java中,我们可以main()通过这两种方式定义方法。

public static void main(String[] args) {          
    System.out.println("Hello World");
}

.

.

public static void main(String... args) {          
    System.out.println("Hello World");
}

Both method takes arrayof Stringarguments. Now consider following scenario.

这两种方法需要arrayString参数。现在考虑以下场景。

    String[] arr=new String[10]; // valid
    String... arr=new String[10];// invalid 

Javanever allows to create an array like this wayString... arr=new String[10];. But in above method implementation javaallows to do so. My question is how javaachieve this two different behavior for two scenarios?

Java永远不允许以这种方式创建数组String... arr=new String[10];。但是在上面的方法实现中java允许这样做。我的问题是如何java在两种情况下实现这两种不同的行为?

采纳答案by Juned Ahsan

... 

is a syntax for method arguments and not for variable definitions. The name of this notation is varargs, which is self explanatory i.e variable number of arguments.

是方法参数的语法,而不是变量定义的语法。这种表示法的名称是varargs,这是不言自明的,即可变数量的参数。

回答by Ankur Lathi

Variable argument or varargs(...)in Java used to write more flexible methods which can accept as many argument as you need not for initialization.

Java 中的变量参数或 varargs(...)用于编写更灵活的方法,这些方法可以接受尽可能多的参数以进行初始化。

回答by fortran

You can use varargs in mainbecause a method declared with varargs (...) is bytecode compatible with a declaration of a method with an array argument (for backwards compatibility). That does not mean that the same syntax is allowed for type declarations.

您可以使用 varargs inmain因为用 varargs (...) 声明的方法与带有数组参数的方法声明的字节码兼容(为了向后兼容)。这并不意味着类型声明允许使用相同的语法。

回答by sanbhat

...refers to varargsand its main intention to make method more readable.

...指的是可变参数及其主要目的是使方法更具可读性

void method(String... args) {

}

can be called as

可以称为

method("a");OR method("a", "b");OR method("a", "b", "c");

method("a");method("a", "b");method("a", "b", "c");

I see no point in using it in variable declaration, we can't do much with

我认为在变量声明中使用它没有意义,我们不能做太多

String... a = {"a", "b"}

An array can anyways be declared with dynamic size

无论如何都可以使用动态大小声明数组

String[] arr = {"a"};

OR

或者

String[] arr = {"a", "b"};