简体   繁体   English

用Java定义一个String数组

[英]Define a String array in Java

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. 两种方法都采用String参数array Now consider following scenario. 现在考虑以下情形。

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

Java never allows to create an array like this way String... arr=new String[10]; Java永远不允许这样创建数组String... arr=new String[10]; . But in above method implementation java allows to do so. 但是在上述方法实现中, java允许这样做。 My question is how java achieve this two different behavior for two scenarios? 我的问题是java在两种情况下如何实现这两种不同的行为?

... 

is a syntax for method arguments and not for variable definitions. 是方法参数而不是变量定义的语法。 The name of this notation is varargs , which is self explanatory ie variable number of arguments. 该符号的名称是varargs ,它可以自我解释,即可变数量的参数。

Java中的可变参数或varargs(...)用于编写更灵活的方法,这些方法可以接受不需要初始化的任意数量的参数。

... refers to varargs and its main intention to make method more readable . ...是指varargs及其主要目的是使方法更具可读性

void method(String... args) {

}

can be called as 可以称为

method("a"); OR method("a", "b"); OR method("a", "b"); OR method("a", "b", "c"); OR 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"};

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). 您可以在main使用varargs,因为用varargs(...)声明的方法与带有数组参数的方法的声明是字节码兼容的(为了向后兼容)。 That does not mean that the same syntax is allowed for type declarations. 这并不意味着类型声明可以使用相同的语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM