zoukankan      html  css  js  c++  java
  • 【转】ArrayList的toArray,也就是list.toArray[new String[list.size()]];,即List转为数组

    【转】ArrayList的toArray

    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();
    		

    结果一运行,报错:

    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);
    		}

    所以第一个重构方法就不是那么好使了。

    实际上,将list世界转化为array的时候,第二种重构方法更方便,用法如下:

    String[] array =new String[list.size()];
    		list.toArray(array);


    
    


    另附,两个重构方法的源码:
    
    
    

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

    2.

    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;

    return a;
    }




    ---- 动动手指关注我!或许下次你又能在我这里找到你需要的答案!ZZZZW与你一起学习,一起进步!
  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/zzzzw/p/5171221.html
Copyright © 2011-2022 走看看