Java automatically converting collections to arguments arrays?

本小妞迷上赌 提交于 2019-12-12 10:31:21

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/33461138/java-automatically-converting-collections-to-arguments-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!