Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java automatically converting collections to arguments arrays?

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.

like image 800
unlimitednzt Avatar asked Nov 01 '15 10:11

unlimitednzt


2 Answers

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.

like image 200
JB Nizet Avatar answered Oct 04 '22 20:10

JB Nizet


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.

like image 39
Tunaki Avatar answered Oct 04 '22 22:10

Tunaki