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

来源:互联网 发布:大六壬排盘软件安卓版 编辑:程序博客网 时间:2024/06/05 13:23

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大于1003).姑且认为最好的String[] y = x.toArray(new String[x.size()]); 

欢迎大家提出你的问题~

1 0
原创粉丝点击