Java - ArratList-> toarray()方法详解

API:http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

ArrayList提供了一个将List转为数组的一个非常方便的方法toArray。toArray有两个重载的方法:
1.list.toArray();
2.list.toArray(T[] a); 对于第一个重载方法,是将list直接转为Object[] 数组; 第二种方法是将list转化为你所需要类型的数组,当然我们用的时候会转化为与list内容相同的类型。

一般而言,我们都是这么写得:
    ArrayList<String> list=new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            list.add(""+i);
        }

        String[] array= (String[]) list.toArray();ArrayList<String> list=new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            list.add(""+i);
        }

        String[] array= (String[]) list.toArray();
然而,运行出错,这是为什么呢? 
错误提示如下:Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Object[] 不可以转化为String[];   需要进行每个元素的单独转换

那么正确的就应该是:
    Object[] arr = list.toArray();
    for (int i = 0; i < arr.length; i++) {
         String e = (String) arr[i];
         System.out.println(e);
    }

由例题可见,第一个重载方法toArray()是不够完善的,而第二个重载方法会显得高效,实用~

下面我贴出两种构造方法的实现过程,大家可以自行体会

public Object[] toArray(); {
        Object[] result = new Object[size];
        System.arraycopy(elementData, 0, result, 0, size);;
        return result;
    }

    public Object[] toArray(Object a[]); {
        if (a.length < size)
            a = (Object[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
        System.arraycopy(elementData, 0, a, 0, size);;
        if (a.length > size)
            a[size] = null;  //@1
        return a;
    }

@1处,为何会置为null呢?
:如果你遇到了类似的问题,你首先做的就是查看API注视,而不是冥思苦想~~
API:[http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray(T[])](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28T%5B%5D%29)
     * <p>If the list fits in the specified array with room to spare
     * (i.e., the array has more elements than the list), the element in
     * the array immediately following the end of the collection is set to
     * <tt>null</tt>.  (This is useful in determining the length of the
     * list <i>only</i> if the caller knows that the list does not contain
     * any null elements.)
*/
这句话的意思是:仅 在调用者知道列表中不包含任何 null 元素时才能用此方法确定列表长度】,
原来的那个list中没有null元素,这样它a[size] = null;
赋值后,在确定list长度时才是有用的.
如果之前的list当中有null元素,就没办法判断哪个是真的长度了。
使用Demo:
1).参数指定空数组,节省空间
String[] y = x.toArray(new String[0]);
2).指定大数组参数浪费时间,采用反射机制
String[] y = x.toArray(new String[100]);  //假设数组size大于100
3).姑且认为最好的
String[] y = x.toArray(new String[x.size()]); 

欢迎大家提出你的问题~

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值