Collection.toArray():将集合转换成数组
Collection接口中有两种toArray()方法
Object[] toArray() Return an Array Containing all of the elements in this collection.
<T> T[] toArray(T[] a) Return an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
两种方法从集合转换成数组,但是实现上有不同。
该方法是一个泛型方法:<T> T[] toArray(T[] a);
如果toArray
方法中没有传递任何参数的话返回的是Object
类型数组。
String [] s= new String[]{
"dog", "lazy", "a", "over", "jumps", "fox", "brown", "quick", "A"
};
List<String> list = Arrays.asList(s);
Collections.reverse(list);
s=list.toArray(new String[0]);//没有指定类型的话会报错
由于JVM优化,new String[0]
作为Collection.toArray()
方法的参数现在使用更好,new String[0]
就是起一个模板的作用,指定了返回数组的类型,0是为了节省空间,因为它只是为了说明返回的类型。详见:https://shipilev.net/blog/2016/arrays-wisdom-ancients/