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);
}
As mentioned earlier, varargs are arrays so we need to work with them just like we'd work with a normal array.
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[].
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With