Java List转数组是Java程序员经常编程使用到的,下面我就详解常见的Java List转数组的3种方法@mikechen
第一种:List的toArray()
首先,大家使用比较多的Java List转换成数组方法是:List的toArray(),或者toArray(T[] a)方法。
下面我先从第一种:toArray()谈起,如果要把一个List直接转化为Object数组,则可以直接使用Object[] o = list.toArray()。
源码如下:
// transient Object[] elementData; 存放list中的各个元素 // private int size; list中元素的个数 public Object[] toArray() { return Arrays.copyOf(elementData, size); }
注意事项:该方法不能指定转换数组的类型,返回值只能是Object()数组。
所以得到返回值后往往需要做类型转换,将Object[]转换为我们需要的类型,具体示例如下:
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); Integer[] a = list.toArray(new Integer[list.size()]);
第二种: list.toArray(T[] a)
这两个方法都是将列表List中的元素转导出为数组,不同的是toArray()方法导出的是Object类型数组,而toArray[T[] a]方法导出的是指定类型的数组。
toArray[T[] a]方法导出的是指定类型的数组,源码如下:
// toArray(T[] a)源码 public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
具体示例如下:
Person[] persons = list.toArray(new Person[list.size()]) // 输出 for(Person person : persons){ System.out.print(person); }
第三种:List for循环转数组
还可以使用List for 循环来转数组,具体示例如下:
//要转换的list集合 List testList = new ArrayList(){{add(“mike”);add(“chen”);}}; //初始化需要得到的数组 String[] array = new String[testList.size()]; //使用for循环得到数组 for(int i = 0; i < testList.size();i++){ array[i] = testList.get(i); }