toArray方法是ArrayList提供的将List转为数组的一个非常方法的方法。其中有有两个重载方法。
method1:list.toArray()
返回:Object[]数组
public Object[] toArray() { return Arrays.copyOf(elementData, size); }
method2:list.toArray(T[])
public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
返回:传入数组的类型的数组
代码演示一
//不带参数的toarray方法 String[] arr = (String[])list.toArray();
运行结果:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at com.test.sofaweb.demo.Demo4.toArrayDemo(Demo4.java:27)
at com.test.sofaweb.demo.Demo4.main(Demo4.java:17)
备注:异常的原因是无法将Object类型的数组强转为String类型的数组
代码演示二
//参数的toarray方法,参数为小于list.size()的数组,list.size()为3 String[] arr = new String[1]; String[] arrNew = list.toArray(arr); for (String s : arrNew) { System.out.println(s); } System.out.println(arr==arrNew);
运行结果
aa
bb
cc
false
备注:当入参数组length小于list.size(),会新建一个同类型的数组来保持list中的元素
代码演示三
//参数的toarray方法,参数为大于list.size()的数组,list.size()为3 String[] arr = new String[5]; String[] arrNew = list.toArray(arr); for (String s : arrNew) { System.out.println(s); } System.out.println(arr==arrNew);
运行结果
aa
bb
cc
null
null
true
备注:当入参数组length小于list.size(),不会新建一个同类型的数组来保持list中的元素,并且会将超出list.size()的空间用“null”来填充
代码演示四
//参数的toarray方法,参数为等于list.size()的数组,list.size()为3 String[] arr = new String[list.size()]; String[] arrNew = list.toArray(arr); for (String s : arrNew) { System.out.println(s); } System.out.println(arr==arrNew);
运行结果
aa
bb
cc
true
备注:当入参数组length小于list.size(),不会新建一个同类型的数组来保持list中的元素,并且也没有填充超出list.size()的空间一说,这样看来这种方法应该是开销最小的ListToArray的方式了。
版权声明:本文为startyangu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。