问题描述
Varargs:
public static void foo(String... string_array) { ... }
与
单数组参数:
public static void bar(String[] string_array) { ... }
Java 1.6似乎接受/拒绝以下内容:
Java 1.6 seems to accept/reject the following:
String[] arr = {"abc", "def", "ghi"};
foo(arr); // accept
bar(arr); // accept
foo("abc", "def", "ghi"); // accept
bar("abc", "def", "ghi"); // reject
假设以上内容是正确/正确的,为什么不总是使用varargs而不是单个数组参数呢?似乎免费增加了呼叫者的灵活性.
Assuming the above is true/correct, why not always use varargs instead of single array param? Seems to add a touch of caller flexiblity for free.
如果有,专家可以共享内部JVM的不同吗?
Can an expert share the internal JVM difference, if there is one?
谢谢.
推荐答案
数组从Java的开始就出现了,而varargs是最近才出现的.因此,许多旧代码仍然很高兴地使用数组.
Arrays have been around from the beginning of Java, while varargs are a fairly recent addition. Thus a lot of older code still happily uses arrays.
还请注意,使用显式数组参数调用通用vararg方法可能会静默地产生与预期不同的行为:
Note also that calling a generic vararg method with an explicit array parameter may silently produce different behaviour than expected:
public <T> void foo(T... params) { ... }
int[] arr = {1, 2, 3};
foo(arr); // passes an int[][] array containing a single int[] element
因此-除了需要大量的工作并没有明显的好处之外-始终不希望用varargs替换旧的数组参数.
Thus - apart from requiring a lot of effort for no clear benefit - it is not always desirable to replace legacy array parameters with varargs.
更不用说您不能这样做的情况,因为方法参数列表中的数组后面还有另一个参数:
Not to mention the cases when you can't, because there is another parameter after the array in the method parameter list:
public void foo(String[] strings, String anotherParam) { ... }
重新排序参数可以从技术上解决此问题,但是这会破坏客户端代码.
Reordering the parameters may technically solve this, however it breaks client code.
更新:有效的Java 2nd. Edition,版本42:明智地使用varargs 对此进行了更详细的说明,并给出了一个具体示例:Java5中对Arrays.asList()
进行了改进以使其具有vararg参数,而使用此(现在已过时)的习惯用法来打印数组时可能会引起意外:
Update: Effective Java 2nd. Edition, Item 42: Use varargs judiciously explains this in more details, giving also a concrete example: Arrays.asList()
was retrofitted in Java5 to have vararg parameters, which may cause surprises when using this (now obsolete) idiom to print an array:
System.out.println(Arrays.asList(myArray));
Update2::仔细检查了源,并说问题是原始类型数组(例如int[]
)发生的.在varargs之前,应这样编写代码:
Update2: Double checked the source, and it says that the problem occurrs with arrays of primitive types, such as int[]
. Before varargs, code like this:
int[] digits = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 4 };
System.out.println(Arrays.asList(digits));
将发出编译错误,因为只有引用类型的数组可以转换为List
.由于使用了varargs,并且对asList
进行了改造,因此上面的代码在没有警告的情况下进行编译,意外的结果类似于"[[I@3e25a5]"
.
would emit a compilation error, because only arrays of reference types could be converted to a List
. Since varargs, and retrofitting asList
, the code above compiles without warnings, and the unintended result is something like "[[I@3e25a5]"
.
这篇关于Java varargs方法参数列表与数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!