toArray方法
在平时得开发中有时候会遇到需要将 list集合转换成 数组的经历,这个时候就可以使用我们的 toArray()方法。那么toArray的具体使用方法和注意事项有哪些呢?
使用
正常情况下我们直接使用创建的List集合直接 .toArray()
来转换成数组
List<String> tetsList = new ArrayList();
Object[] objects = tetsList.toArray();
如上代码,我们可以发现引入的局部变量的类型和我们list集合的String类型并不一直,而是Object,这是因为toArra()方法的返回值本身就是 Object 。并且直接使用 toArray 无参方法存在问题,若强转为其他类型数组,将会出现 ClassCastException 错误
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify the returned array.
This method acts as bridge between array-based and collection-based APIs.
返回值:
an array containing all of the elements in this list in proper sequence
请参阅:
Arrays.asList(Object[])
@NotNull
Object[] toArray();
从以上的代码中可以 看出,可以通过 Arrays.asList(Object[])
这样的方式来改变返回的类型。
List<String> tetsList = new ArrayList();
String[] strings = tetsList.toArray(new String[0]);
使用 toArray(T[] array) 的形式。在使用中也有一些需要了解的东西:
说明:使用 toArray 带参方法,数组空间大小的 length的取值:
# toArray(T[] array)
#length:array长度 size:list长度
1、等于0,动态创建与size相同的数组,在性能上是最好的。
2、大于0 并且小于 size。程序会重新创建大小等于size的数组,但是会增加GC的负担。
3、等于size,在高并发情况下,可能会出现数组创建完成之后,size正在发生变化的情况,这样子也会增加GC的负担。
4、大于 size的情况下,会在超出的size中插入null。造成空间浪费,并且也会存在一定的不良隐患。
总结
在将list转换成数组的过程中,使用 toarray(T[] array) 带参方法是比较好的。并且将参数的数组的length设置为 0最佳。