Java自动将集合转换为参数数组? [英] Java automatically converting collections to arguments arrays?

查看:29
本文介绍了Java自动将集合转换为参数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java..."数组参数语法可以接收一个数组作为参数,或者只是传递给方法的许多参数.但是,我注意到它也适用于集合:

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");
}

这无需我调用 toArray() 方法即可编译和运行.幕后发生了什么?是否有针对此语法的这种自动转换"的其他方法?

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?

顺便说一句,我使用的是 Java 1.7.

BTW, I'm using Java 1.7.

推荐答案

它不会将集合转换为数组.它将集合本身​​作为第一个 vararg 参数传递.测试方法因此接收一个由一个元素组成的数组,这个元素就是 ArrayList.

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");

System.out.println(Arrays.toString(objects);

或者使用调试器.

这篇关于Java自动将集合转换为参数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆