import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListToArrays { public static void main(String[] args) { List<String> list = new ArrayList<String>() { private static final long serialVersionUID = 1L; { add("l"); add("2"); add("3"); add("4"); } }; /** * List to Arrays,下面的两种用法在功能上是等价的, * 建议使用:list.toArray(new String[list.size()]); */ // String[] arrsys = list.toArray(new String[0]); String[] arrsys = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(arrsys)); } }
原因:
最终使用的是API:System.java中的
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
,如果参数数组的长度与预期不符,则会走额外的判断逻辑。既然很容易取到list的size,并且这个size在数组中是必需的,那传个正确的是不是更好些
/** * Copies an array from the specified source array, beginning at the * specified position, to the specified position of the destination array. * A subsequence of array components are copied from the source * array referenced by <code>src</code> to the destination array * referenced by <code>dest</code>. The number of components copied is * equal to the <code>length</code> argument. The components at * positions <code>srcPos</code> through * <code>srcPos+length-1</code> in the source array are copied into * positions <code>destPos</code> through * <code>destPos+length-1</code>, respectively, of the destination * array. * <p> * If the <code>src</code> and <code>dest</code> arguments refer to the * same array object, then the copying is performed as if the * components at positions <code>srcPos</code> through * <code>srcPos+length-1</code> were first copied to a temporary * array with <code>length</code> components and then the contents of * the temporary array were copied into positions * <code>destPos</code> through <code>destPos+length-1</code> of the * destination array. * <p> * If <code>dest</code> is <code>null</code>, then a * <code>NullPointerException</code> is thrown. * <p> * If <code>src</code> is <code>null</code>, then a * <code>NullPointerException</code> is thrown and the destination * array is not modified. * <p> * Otherwise, if any of the following is true, an * <code>ArrayStoreException</code> is thrown and the destination is * not modified: * <ul> * <li>The <code>src</code> argument refers to an object that is not an * array. * <li>The <code>dest</code> argument refers to an object that is not an * array. * <li>The <code>src</code> argument and <code>dest</code> argument refer * to arrays whose component types are different primitive types. * <li>The <code>src</code> argument refers to an array with a primitive * component type and the <code>dest</code> argument refers to an array * with a reference component type. * <li>The <code>src</code> argument refers to an array with a reference * component type and the <code>dest</code> argument refers to an array * with a primitive component type. * </ul> * <p> * Otherwise, if any of the following is true, an * <code>IndexOutOfBoundsException</code> is * thrown and the destination is not modified: * <ul> * <li>The <code>srcPos</code> argument is negative. * <li>The <code>destPos</code> argument is negative. * <li>The <code>length</code> argument is negative. * <li><code>srcPos+length</code> is greater than * <code>src.length</code>, the length of the source array. * <li><code>destPos+length</code> is greater than * <code>dest.length</code>, the length of the destination array. * </ul> * <p> * Otherwise, if any actual component of the source array from * position <code>srcPos</code> through * <code>srcPos+length-1</code> cannot be converted to the component * type of the destination array by assignment conversion, an * <code>ArrayStoreException</code> is thrown. In this case, let * <b><i>k</i></b> be the smallest nonnegative integer less than * length such that <code>src[srcPos+</code><i>k</i><code>]</code> * cannot be converted to the component type of the destination * array; when the exception is thrown, source array components from * positions <code>srcPos</code> through * <code>srcPos+</code><i>k</i><code>-1</code> * will already have been copied to destination array positions * <code>destPos</code> through * <code>destPos+</code><i>k</I><code>-1</code> and no other * positions of the destination array will have been modified. * (Because of the restrictions already itemized, this * paragraph effectively applies only to the situation where both * arrays have component types that are reference types.) * * @param src the source array. * @param srcPos starting position in the source array. * @param dest the destination array. * @param destPos starting position in the destination data. * @param length the number of array elements to be copied. * @exception IndexOutOfBoundsException if copying would cause * access of data outside array bounds. * @exception ArrayStoreException if an element in the <code>src</code> * array could not be stored into the <code>dest</code> array * because of a type mismatch. * @exception NullPointerException if either <code>src</code> or * <code>dest</code> is <code>null</code>. */ public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
ArrayList.java
/** * Returns an array containing all of the elements in this list in proper * sequence (from first to last element); the runtime type of the returned * array is that of the specified array. If the list fits in the * specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of * this list. * * <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.) * * @param a the array into which the elements of the list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ 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; }
如果参数数组长度与List不符,会增加相关的处理逻辑:
Arrays.java
/** * Copies the specified array, truncating or padding with nulls (if necessary) * so the copy has the specified length. For all indices that are * valid in both the original array and the copy, the two arrays will * contain identical values. For any indices that are valid in the * copy but not the original, the copy will contain <tt>null</tt>. * Such indices will exist if and only if the specified length * is greater than that of the original array. * The resulting array is of the class <tt>newType</tt>. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls * to obtain the specified length * @throws NegativeArraySizeException if <tt>newLength</tt> is negative * @throws NullPointerException if <tt>original</tt> is null * @throws ArrayStoreException if an element copied from * <tt>original</tt> is not of a runtime type that can be stored in * an array of class <tt>newType</tt> * @since 1.6 */ public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
List.java对这个接口的定义:
/** * Returns an array containing all of the elements in this list in * proper sequence (from first to last element); the runtime type of * the returned array is that of the specified array. If the list fits * in the specified array, it is returned therein. Otherwise, a new * array is allocated with the runtime type of the specified array and * the size of this list. * * <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 list 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.) * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose <tt>x</tt> is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of <tt>String</tt>: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that <tt>toArray(new Object[0])</tt> is identical in function to * <tt>toArray()</tt>. * * @param 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. * @return an array containing the elements of this list * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list * @throws NullPointerException if the specified array is null */ <T> T[] toArray(T[] a);