博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
List toArrays()
阅读量:6936 次
发布时间:2019-06-27

本文共 10409 字,大约阅读时间需要 34 分钟。

 

import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ListToArrays {    public static void main(String[] args) {        List
list = 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 by src to the destination array     * referenced by dest. The number of components copied is     * equal to the length argument. The components at     * positions srcPos through     * srcPos+length-1 in the source array are copied into     * positions destPos through     * destPos+length-1, respectively, of the destination     * array.     * 

* If the src and dest arguments refer to the * same array object, then the copying is performed as if the * components at positions srcPos through * srcPos+length-1 were first copied to a temporary * array with length components and then the contents of * the temporary array were copied into positions * destPos through destPos+length-1 of the * destination array. *

* If dest is null, then a * NullPointerException is thrown. *

* If src is null, 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: *

    *
  • The src argument refers to an object that is not an * array. *
  • The dest argument refers to an object that is not an * array. *
  • The src argument and dest argument refer * to arrays whose component types are different primitive types. *
  • The src argument refers to an array with a primitive * component type and the dest argument refers to an array * with a reference component type. *
  • The 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: *

    *
  • The srcPos argument is negative. *
  • The destPos argument is negative. *
  • The 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 static 
T[] 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/

你可能感兴趣的文章
最新app源码下载:200款优秀Android项目源码
查看>>
PHP/Yii2操作Cookie,常见问题以及注意事项
查看>>
支持向量机(五)SMO算法
查看>>
编译Android源码
查看>>
聚类分析算法---学习
查看>>
通过SQL Server命令行启动及停止SQL服务的方法
查看>>
笔记本电脑不显示电量图标-20180103
查看>>
JVM致命错误日志(hs_err_pid.log)解读
查看>>
springboot~openfeign从此和httpClient说再见
查看>>
CSRF攻击和防护
查看>>
FileUpload控件实例应用 上传文件
查看>>
springboot入门_数据库访问_jdbcTemplate
查看>>
迭代器 Iterator
查看>>
0初识Linux
查看>>
1048 Find Coins
查看>>
弱语法
查看>>
kafka api
查看>>
[WC2019] 数树
查看>>
fedora23的打印服务
查看>>
人类进程(一)
查看>>