package toarray; import java.util.List; public class TestOne { @SuppressWarnings("unchecked") public static void main(String[] args) { /** * * 1、创建一个ArrayList对象,默认创建一个长度是10的数组 * * 2、add时改变容量size public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } * * * 3、toArray() Arrays拷贝一份数据返回Object[]类型 public Object[] toArray() { return Arrays.copyOf(elementData, size); } * * 4. toArray(T[] a) 传入数组参数, 返回数组类型是参数数组类型 1)当参数数组长度length小于 ArrayList对象的size,Arrays拷贝一份数据返回 2)...................................大于................. System.arraycopy拷贝一份数据返回,空余位赋null值 @SuppressWarnings("unchecked") 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; } */ @SuppressWarnings("rawtypes") List list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); String[] arr1 = (String[]) list.toArray(); String[] arr2 = (String[]) list.toArray(new String[6]); for(String str : arr1){ //Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; System.out.println(str); } for(String str : arr2){ System.out.println(str); } } }