Java 中 String[] 和 String... 有什么不同
在Java中,在定义方法的时候,作为参数的 String[]
和 String...
有什么不同呢?这是经常会被问到的一个问题。也就是说,下面的代码有什么区别
public static void main(String[] args)
{
System.out.println("foo");
}
和
public static void main(String... args)
{
System.out.println("bar");
}
String[]
和 String...
在内部是相同的,即。 例如,一个字符串数组。 不同之处在于,当我们的方法的参数个数是不固定的时候要使用 String... ,调用如下方法:
public void myMethod( String... foo ) {
System.out.println( foo[0] );
}
myMethod( "a", "b", "c" );
// 或者
myMethod( new String[]{ "a", "b", "c" } );
// 或者也可以不传参数
myMethod();
如果将参数声明为 String 数组时,必须像下面一样进行调用:
public void myMethod( String[] foo ) {
// do something
System.out.println( foo[0] );
}
// 编译错误!!!
myMethod( "a", "b", "c" );
// 编译错误!!!
myMethod();
// 只能使用这种方式
myMethod( new String[]{ "a", "b", "c" } );
约定使用 String[]
作为 main 方法的参数,但使用 String...
也可以,因为当我们使用可变参数时,可以像调用以数组作为参数的方法和一样将其作为参数来调用方法,它将是方法体内的一个数组。
还有一个比较重要的事情是,当使用可变参数时,它必须是方法的最后一个参数,并且一个方法只能有一个可变参数。
使用 ...
替代 []
的优势
-
节省内存 在上面示例中使用
mymethod(int [])
。当我们在main方法中创建一个数组“Data[]”时,它们会创建新对象并获得内存空间。以及当我们创建方法并定义参数时:getid(int []) -> 这将在内存中创建另一个对象,因此我们在内存中有 2 个彼此相同的对象 -
使用“...”时可以不传递任何内容 可以在调用“getid”方法时不传递任何内容,并且它们可以正常工作而不会出现任何错误,这对于使程序更稳定非常有帮助,例如
... public static void main(String []arg) { new test().getid(); } ...
[]
,调用 getid 方法时不传递任何内容的话,它会在编译时报错。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。