I know that the Java "..." array argument syntax can receive as a parameter an array, or just many parameters passed to the method. However, I noticed that it does so for Collections too:
public static void main(String[] args) {
Collection<Object> objects = new ArrayList<>();
test(objects);
}
public static void test (Object...objects) {
System.out.println("no compile errors");
}
This compiles and runs without me needing to call the toArray()
method. What is happening behind the scene? Are there additional methods of this "auto-conversion" for this syntax?
BTW, I'm using Java 1.7.
It doesn't convert the collection to an array. It pass the collection itself as the first vararg argument. The test method thus receives an array of one element, and this element is the ArrayList.
This can be found easily by replacing
System.out.println("no compile errors");
by
System.out.println(Arrays.toString(objects);
Or by using a debugger.
A Collection<Object>
is also an Object
so when you invoke test
with
Collection<Object> objects = new ArrayList<>();
test(objects);
it will be invoked with a single parameter that is your collection: the method will receive an array having a single element.
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