Archive for 7月 2009

java ArrayList toArray()方法的注意   Leave a comment

     ArrayList类扩展AbstractList并执行List接口。ArrayList支持可随需要而增长的动态数组。
     ArrayList有如下的构造函数:
  
         ArrayList( )
         ArrayList(Collection c)
         ArrayList(int capacity)
 如果调用new ArrayList()构造时,其默认的capacity(初始容量)为10。
 参见ArrayList源码,其中是这样定义的:
     public ArrayList() {
  this(10);
      }
 默认初始化内部数组大小为10。
    程序编译后执行ArrayList.toArray(),把ArrayList转化为数组时,该数组大小仍为capacity(为10)。
 当装入的数据和capacity值不等时(小于capacity),比如只装入了5个数据,数组
中后面的(capacity –
size)个对象将置为null,此时当数组强制类型转换时,容易出现一些问题,如java.lang.ClassCastException异常等。
 解决办法是:在用ArrayList转化为数组装数据后,使用trimToSize()重新设置数组的真实大小。
   toArray()正确使用方式如下:
         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足够大,就会把数据全放进去,返回的数组也是指向这个数组,(数组多余的空间存储的是null对象);要是不够大,就申请一个跟参数同样类型的数组,把值放进去,然后返回。

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

参考代码:
   ArrayList result=GetResult();
   int n=result.size();
   String[][] myArray=new String[n][]; //定义二维数组

   for (int i=0;i<n;i++)   //构造二维数组
   {
     ArrayList tempArray= (ArrayList)result.get(i);
     myArray[i]=(String[])tempArray.toArray();      //此处会出现java.lang.ClassCastException的错误
   }

   正确方式
   for (int i=0;i<n;i++)   //构造二维数组
       {
             ArrayList tempArray= (ArrayList)result.get(i);
             myArray[i]=(String[])tempArray.toArray(new String[0]);    //注意此处的写法
        }

Posted 2009年07月19日 by gw8310 in 未分类