Collection.toArray()和Collection.toArray之间差(对象OBJ []) [英] Difference between Collection.toArray() and Collection.toArray(Object obj[])

查看:202
本文介绍了Collection.toArray()和Collection.toArray之间差(对象OBJ [])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据Java文档的toArray()
返回包含此collection中所有元素的数组。

According to java doc for toArray() Returns an array containing all of the elements in this collection.

和的toArray(obj对象[])。
返回包含此collection中所有元素的数组;返回数组的运行时类型是指定数组的。

and toArray(Object obj[]). Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

第一的toArray()我理解,但第二次的toArray(obj对象[])我不能understand.Please用例子来解释。

first toArray() i understand but second toArray(Object obj[]) i can't understand.Please explain with example.

推荐答案

一个是通用的,另一种是不。 的toArray()将返回对象[] ,而的toArray(T [])将返回一个类型的数组 T []

One is generic, the other isn't. toArray() will return Object[] while toArray(T[]) will return an array of type T[].

示例:

public static void main(String[] args) {
    Object[] baseArray = new ArrayList<String>().toArray();
    System.out.println(baseArray.getClass().getCanonicalName());

    String[] improvArray = new ArrayList<String>().toArray(new String[5]);
    System.out.println(improvArray.getClass().getCanonicalName());
}

输出:

java.lang.Object[]
java.lang.String[]

这篇关于Collection.toArray()和Collection.toArray之间差(对象OBJ [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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