本文共 10409 字,大约阅读时间需要 34 分钟。
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ListToArrays { public static void main(String[] args) { Listlist = new ArrayList () { 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 bysrc
to the destination array * referenced bydest
. The number of components copied is * equal to thelength
argument. The components at * positionssrcPos
through *srcPos+length-1
in the source array are copied into * positionsdestPos
through *destPos+length-1
, respectively, of the destination * array. ** If the
src
anddest
arguments refer to the * same array object, then the copying is performed as if the * components at positionssrcPos
through *srcPos+length-1
were first copied to a temporary * array withlength
components and then the contents of * the temporary array were copied into positions *destPos
throughdestPos+length-1
of the * destination array. ** If
dest
isnull
, then a *NullPointerException
is thrown. ** If
src
isnull
, then a *NullPointerException
is thrown and the destination * array is not modified. ** Otherwise, if any of the following is true, an *
ArrayStoreException
is thrown and the destination is * not modified: *
src
argument refers to an object that is not an * array. * dest
argument refers to an object that is not an * array. * src
argument and dest
argument refer * to arrays whose component types are different primitive types. * src
argument refers to an array with a primitive * component type and the dest
argument refers to an array * with a reference component type. * src
argument refers to an array with a reference * component type and the dest
argument refers to an array * with a primitive component type. * * Otherwise, if any of the following is true, an * IndexOutOfBoundsException
is * thrown and the destination is not modified: *
srcPos
argument is negative. * destPos
argument is negative. * length
argument is negative. * srcPos+length
is greater than * src.length
, the length of the source array. * destPos+length
is greater than * dest.length
, the length of the destination array. * * Otherwise, if any actual component of the source array from * position srcPos
through * srcPos+length-1
cannot be converted to the component * type of the destination array by assignment conversion, an * ArrayStoreException
is thrown. In this case, let * k be the smallest nonnegative integer less than * length such that src[srcPos+
k]
* cannot be converted to the component type of the destination * array; when the exception is thrown, source array components from * positions srcPos
through * srcPos+
k-1
* will already have been copied to destination array positions * destPos
through * destPos+
k-1
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 src
* array could not be stored into the dest
array * because of a type mismatch. * @exception NullPointerException if either src
or * dest
is null
. */ 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. * *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 * null. (This is useful in determining the length of the * list only 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[] 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 null. * 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 newType. * * @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 newLength is negative * @throws NullPointerException if original is null * @throws ArrayStoreException if an element copied from * original is not of a runtime type that can be stored in * an array of class newType * @since 1.6 */ public staticT[] copyOf(U[] original, int newLength, Class 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. * *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 null. * (This is useful in determining the length of the list only if * the caller knows that the list does not contain any null elements.) * *
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. * *Suppose x is a list known to contain only strings. * The following code can be used to dump the list into a newly * allocated array of String: * *
* String[] y = x.toArray(new String[0]);* * Note that toArray(new Object[0]) is identical in function to * toArray(). * * @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[] toArray(T[] a);
转载地址:http://astjl.baihongyu.com/