Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the component type for the varargs array determined?

When you use varargs, how is the component type of the resulting array determined?

For example, is this program guaranteed to print true or is its behaviour technically unspecified?

public static void main(String[] args) {
    foo("", 0);
}

static <T> void foo(T... arr) {
    System.out.println(arr.getClass() == Serializable[].class);
} 
like image 960
Paul Boddington Avatar asked Mar 21 '16 21:03

Paul Boddington


People also ask

Is varargs an array?

As mentioned earlier, varargs are arrays so we need to work with them just like we'd work with a normal array.

How does Varargs work in Java?

Syntax of Varargs Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].


1 Answers

I ran this code and the output tells you have no guarantees (at least if classes have more than one common ancestor on different hierarchy branches)

Honestly I don't know the reasons behind this magic, but I just could not post it as a comment

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{

  interface A{}
  interface B{}
  class AB implements A, B {}
  class BA implements A, B {}

    public static void main (String[] args) throws java.lang.Exception
    {
        foo(new AB(), new BA());
        foo2(new AB(), new BA());
    }

    static <T> void foo(T... arr) {
        System.out.println(arr.getClass() == A[].class);
    }

    static <T> void foo2(T... arr) {
        System.out.println(arr.getClass() == B[].class);
    } 
}

output

true
false

More weird things:

If interface B is declared before interface A, result is the opposite:

false
true

Changing order of arguments in method call, method declaration order and order of interfaces in implements block does not make effect for me (1.8.0_51).

like image 61
AdamSkywalker Avatar answered Oct 13 '22 01:10

AdamSkywalker