Java varargs method param list vs. array

41,782

Solution 1

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.

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

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.

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 inadvertently broke a lot of existing code may cause surprises when using this (now obsolete) idiom to print an array:

System.out.println(Arrays.asList(myArray));

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));

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]".

Solution 2

The main reason not to specify everything as varargs is that it doesn't always make sense. For example, if InputStream.read(byte[]) where defined as `read(byte...) then the following call would be valid:

myInputStream.read(0, 1, 2, 3);

This would create a 4-element byte array, pass it in and then discard it.

Solution 3

A vararg is simple syntactic sugar for an array.

if you call foo("abc", "def", "ghi"); then compiler will call it as foo(new String[] {"abc", "def", "ghi"});

compiler will create one new array and pass it to foo(). One can't have both foo(String...) and foo(String[]). Since both are functionally same.

Solution 4

in foo you specify three params, you would have to call bar like this:

 bar(new String[]{"abc", "def", "ghi"});

so that you only call it with one parameter, that is the String[] in this case this has alsmost nothing to do with internals, your method signature for the method bar simply states that it only has one param, whereas foo has n params which are all strings

Solution 5

This is, how varargs are defined. The varargs extension do not make every array accepting function a varargs function. You have to call bar like this:

bar(new String[]{"abc", "def", "ghi"})
Share:
41,782
kevinarpe
Author by

kevinarpe

LinkedIn Profile: https://hk.linkedin.com/pub/kevin-arpe/12/4a4/277 My open source libraries: Papaya for Java: https://github.com/kevinarpe/kevinarpe-papaya Rambutan for Python3: https://github.com/kevinarpe/kevinarpe-rambutan3 I specialise in answering older -- perhaps forgotten -- questions, and making corrections. Best answer: How to handle multipart/alternative mail with JavaMail?

Updated on July 09, 2022

Comments

  • kevinarpe
    kevinarpe almost 2 years

    Varargs:

    public static void foo(String... string_array) { ... }
    

    versus

    Single array param:

    public static void bar(String[] string_array) { ... }
    

    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
    

    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.

    Can an expert share the internal JVM difference, if there is one?

    Thanks.

  • user102008
    user102008 almost 13 years
    "passes a String[][] array containing a single String[] element" can't reproduce this
  • hotshot309
    hotshot309 over 12 years
    To clarify, you can include another parameter in the signature that doesn't take varargs--but the vararg-accepting parameter has to go last. Also, in the example above, calling foo(arr); makes the compiler generate a String[] containing the String[] that you passed in. In other words, it generates a two-dimensional String array, which is a String[][].
  • Joe Coder
    Joe Coder about 12 years
    Totally wrong. Passing a non-primitive array to a varargs parameter will NOT result in a two-dimensional array! Explained here and easily tested.
  • Péter Török
    Péter Török about 12 years
    @JoeCoder, not totally wrong, only imprecise. Please see my update.
  • kevinarpe
    kevinarpe almost 8 years
    The methods aren't invoked until the objects are accessed: Surprising! Does this mean if I don't access the objects in a method, they are never called? Also, did you compile and run this code to confirm the behaviour?
  • Ken T.
    Ken T. over 7 years
    The reason the object parameters aren't invoked in the example I gave is because they are embedded in the object [] array. They will be invoked when the array members are processed, but not at the time of being pushed on the stack for the original method invocation.
  • Quelklef
    Quelklef about 3 years
    Perhaps I am mistaken, but I believe this to be incorrect: Java is an eagerly-evaluated language. Take a look at this code for instance. (tio.run link)