Arrays.asList(s)使用上の注意

1789 ワード

1,パラメータnull Arrays.asList(null)/java.lang.Null PointerException
2,asListは基本データ型の配列を操作し,直接出力戻り値をアドレスとする
int[] array02 = new int[]{1,2,3,4,5,6};
//Object list02 = Arrays.asList(array02);//     List
System.out.println(Arrays.asList(array02));//      

3,asListはStringタイプの配列を操作し,返されるListサイズは固定し,remove/addメソッドは使用できない.
String[] array = new String[]{"1","2","3","4","5","6"};
System.out.println(Arrays.asList(array));
//sList.add("1");//  :java.lang.UnsupportedOperationException
//sList.remove("1");//  :java.lang.UnsupportedOperationException
//  :   ArrayList   ArrayList ,  Arrays    

Arrays.asList(array)は、次の方法を呼び出します.
/**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * the returned list "write through" to the array.)  This method acts
     * as bridge between array-based and collection-based APIs, in
     * combination with {@link Collection#toArray}.  The returned list is
     * serializable and implements {@link RandomAccess}.
     *
     * 

This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: *


     *     List stooges = Arrays.asList("Larry", "Moe", "Curly");
     * 
*
* @param the class of the objects in the array
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static List asList(T... a) {
return new ArrayList<>(a);
}
:http://javapub.iteye.com/blog/1551604