java 可变参数数组参数和普通数组参数有什么区别?
What's difference between java vararg array param and normal array param?
有两种函数声明:
void f(String ... s) {
System.out.println(s.length);
}
void g(String [] s){
System.out.println(s.length);
}
都可以,我猜"f()"只是g()的一种语法糖?
当使用 f() 时,java 编译器仍然会创建一个内部数组 s,对还是错? ---- 我检查了 Intellij 中的 class 文件,似乎 f() 的反汇编代码仍然是 String... 而不是 String[]
你能帮忙解释一下吗?非常感谢。
问:java可变参数数组参数和普通数组参数有什么区别?
见https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position.
问:都可以,我猜"f()"只是g()的一种语法糖?
是的。
It is still true that multiple arguments must be passed in an array,
but the varargs feature automates and hides the process.
问:使用f()时,java编译器还是会创建一个s的内部数组,对不对? ---- 我检查了 Intellij 中的 class 文件,似乎 f() 的反汇编代码仍然是 String... 而不是 String[]
它是句柄数组,参见How does JVM implement the varargs?
另外本人完全支持参考文献最后的说法:
So when should you use varargs? As a client, you should take advantage
of them whenever the API offers them. Important uses in core APIs
include reflection, message formatting, and the new printf facility.
As an API designer, you should use them sparingly, only when the
benefit is truly compelling. Generally speaking, you should not
overload a varargs method, or it will be difficult for programmers to
figure out which overloading gets called.
有两种函数声明:
void f(String ... s) {
System.out.println(s.length);
}
void g(String [] s){
System.out.println(s.length);
}
都可以,我猜"f()"只是g()的一种语法糖?
当使用 f() 时,java 编译器仍然会创建一个内部数组 s,对还是错? ---- 我检查了 Intellij 中的 class 文件,似乎 f() 的反汇编代码仍然是 String... 而不是 String[]
你能帮忙解释一下吗?非常感谢。
问:java可变参数数组参数和普通数组参数有什么区别?
见https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position.
问:都可以,我猜"f()"只是g()的一种语法糖?
是的。
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process.
问:使用f()时,java编译器还是会创建一个s的内部数组,对不对? ---- 我检查了 Intellij 中的 class 文件,似乎 f() 的反汇编代码仍然是 String... 而不是 String[]
它是句柄数组,参见How does JVM implement the varargs?
另外本人完全支持参考文献最后的说法:
So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.