unlimitednzt
unlimitednzt

Reputation: 1065

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.

Upvotes: 13

Views: 3155

Answers (3)

Paul Boddington
Paul Boddington

Reputation: 37645

What is happening here is that the method receives an array of length 1 containing a single Collection.

Most of the time, the signature

method(Object... objs)

should be avoided, as it will accept any sequence of parameters, even primitives as these get auto boxed.

Upvotes: 4

Tunaki
Tunaki

Reputation: 137094

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.

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691765

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.

Upvotes: 13

Related Questions