List.toArray的正确使用

在程序中,往往得到一个List, 程序要求对应赋值给一个array,   可以这样写程序:   

for example:   

Long [] l = new Long[list.size()];
for(int i=0;i<list.size();i++){
	l[i] = (Long) list.get(i);
}

 

 

  

要写这些code,似乎比较繁琐,其实List提供了toArray()的方法,但是要使用不好,就会有ClassCastException   究竟这个是如何产生的,且看代码:  

-----------------------------------------------------------------------------------   

List list = new ArrayList(); 
list.add(new Long(1));
list.add(new Long(2));
list.add(new Long(3));
list.add(new Long(4));   
Long[] l = (Long[])list.toArray();// 代码会抛java.lang.ClassCastException。  
for(int i=0; i<l.length; i++)   
  System.out.println(l[i].longValue());

    

-----------------------------------------------------------------------------------    

当然,为了读出值来,你可以这样code:   

-----------------------------------------------------------------------------------   

Object [] a = list.toArray();   
for(int i=0;i<a.length;i++)
  System.out.println(((Long)a[i]).longValue()); 

   

-----------------------------------------------------------------------------------   

但是让数组丢失了类型信息,这个不是我们想要得。哭正确使用方式:  

-----------------------------------------------------------------------------------   

Long[] l = new Long[];    
list.toArray(l);   
Long[] l = (Long []) list.toArray(new Long[0]); 
Long [] a = new Long[];   
Long [] l = (Long []) list.toArray(a);

    

-----------------------------------------------------------------------------------   

java sdk doc 上讲:   

public Object[] toArray(Object[] a)   

a--the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.   

如果这个数组a足够大,就会把数据全放进去,返回的数组也是指向这个数组;  

要是不够大,就申请一个跟参数同样类型的数组,把值放进去,然后返回。  

注意的是:你要是传入的参数为9个大小,而list里面有5个object,那么其他的四个很可能是null , 使用的时候要注意。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值