在 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
Define a String array in Java
提问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 array
of String
arguments. Now consider following scenario.
这两种方法需要array
的String
参数。现在考虑以下场景。
String[] arr=new String[10]; // valid
String... arr=new String[10];// invalid
Java
never allows to create an array like this wayString... arr=new String[10];
. But in above method implementation java
allows to do so. My question is how java
achieve this two different behavior for two scenarios?
Java
永远不允许以这种方式创建数组String... arr=new String[10];
。但是在上面的方法实现中java
允许这样做。我的问题是如何java
在两种情况下实现这两种不同的行为?
采纳答案by Juned Ahsan
回答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 main
because 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"};