`

Collection的toArray()使用上需要注意的地方

阅读更多
Collection在很多情况下需要转换为数组来处理(很多接口方法都使用array作为参数)。
Collection的toArray()方法返回的Object[],是不能被强制转换为子元素类型的
例如:
List l=new ArrayList();
l.add("a");
l.add("b");
String[] strs=(String[])l.toArray();//throw ClassCastException

通常的做法是:
String[] strs=new String[l.size()];
l.toArray(strs);

toArray(T[] a)方法有个比较怪异的地方:
List l=new ArrayList();   
l.add("a");   
l.add("b");   
String[] strs=new String[4];//比List多2个元素   
for(int i=0;i<strs.length;i++){//填充4个字符串"x”   
     strs[i]="x";   
}   
String[] newStrs=(String[]) l.toArray(strs);
System.out.println(newStrs==strs);//为了确定是否传入的参数对象和返回的是同一个对象。
for(int i=0;i<strs.length;i++){   
   System.out.println(strs[i]);   
}

得到的结果是:
  • true
  • a
  • b
  • null
  • x

JAVA API文档的说明:
引用
toArray
<T> T[] toArray(T[] a)返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。如果指定的数组能容纳该 collection,则返回包含此 collection 元素的数组。否则,将根据指定数组的运行时类型和此 collection 的大小分配一个新数组。
如果指定的数组能容纳 collection 并有剩余空间(即数组的元素比 collection 的元素多),那么会将数组中紧跟在 collection 末尾的元素设置为 null。(这对确定 collection 的长度很有用,但只有 在调用方知道此 collection 没有包含任何 null 元素时才可行。)

如果此 collection 对其迭代器返回的元素顺序做出了某些保证,那么此方法必须以相同的顺序返回这些元素。

像 toArray 方法一样,此方法充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。更进一步说,此方法允许在输出数组的运行时类型上进行精确控制,并且在某些情况下,可以用来节省分配开销。

假定 l 是只包含字符串的一个已知 List。以下代码用来将该列表转储到一个新分配的 String 数组:

     String[] x = (String[]) v.toArray(new String[0]);
注意,toArray(new Object[0]) 和 toArray() 在功能上是相同的。


参数:
a - 存储此 collection 元素的数组(如果其足够大);否则,将为此分配一个具有相同运行时类型的新数组。
返回:
包含此 collection 元素的数组
抛出:
ArrayStoreException - 指定数组的运行时类型不是此 collection 每个元素运行时类型的超类型。
NullPointerException - 如果指定的数组为 null。
2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics