• 正确使用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();
            for(int i=0; i<l.length; i++)
                System.out.println(l[i].longValue());
    -----------------------------------------------------------------------------------

    红色代码会抛java.lang.ClassCastException。
    当然,为了读出值来,你可以这样code:
    -----------------------------------------------------------------------------------
            Object [] a =  list.toArray();
            for(int i=0;i<a.length;i++)
                System.out.println(((Long)a[i]).longValue());
    -----------------------------------------------------------------------------------
    但是让数组丢失了类型信息,这个不是我们想要得。:(
    正确使用方式:
    -----------------------------------------------------------------------------------
    1. Long[] l = new Long[<total size>];
       list.toArray(l);
     
    2. Long[] l = (Long []) list.toArray(new Long[0]);

    3. Long [] a = new Long[<total size>];
        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 , 使用的时候要注意。


    http://blog.csdn.net/lliei/article/details/302232 ;
  • 相关阅读:
    UITabbarItem只显示图标
    [转]translatesAutoresizingMaskIntoConstraints详解
    [转载]podfile语法
    获取数组NSArray元素的className
    HTTP的FormData和Payload的传输格式
    WCDB错误"No matching constructor for initialization of 'WCTColumnBinding'"
    UIStakView的添加与移除
    为什么说Python采用的是基于值的内存管理模式?
    PostgreSQL数据库
    标准库 time
  • 原文地址:https://www.cnblogs.com/superJF/p/4398765.html
Copyright © 2020-2023  润新知